diff --git a/.github/labeler.yml b/.github/labeler.yml index c1d55fb3f7..44001174ca 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -143,6 +143,11 @@ integration:hanlp: - any-glob-to-any-file: "integrations/hanlp/**/*" - any-glob-to-any-file: ".github/workflows/hanlp.yml" +integration:hpc-ai: + - changed-files: + - any-glob-to-any-file: "integrations/hpc_ai/**/*" + - any-glob-to-any-file: ".github/workflows/hpc_ai.yml" + integration:jina: - changed-files: - any-glob-to-any-file: "integrations/jina/**/*" diff --git a/.github/workflows/CI_coverage_comment.yml b/.github/workflows/CI_coverage_comment.yml index 0db73a995e..6e3dc80a4d 100644 --- a/.github/workflows/CI_coverage_comment.yml +++ b/.github/workflows/CI_coverage_comment.yml @@ -28,6 +28,7 @@ on: - "Test / github" - "Test / google-genai" - "Test / hanlp" + - "Test / hpc_ai" - "Test / jina" - "Test / kreuzberg" - "Test / langfuse" diff --git a/.github/workflows/hpc_ai.yml b/.github/workflows/hpc_ai.yml new file mode 100644 index 0000000000..6487ce7f46 --- /dev/null +++ b/.github/workflows/hpc_ai.yml @@ -0,0 +1,136 @@ +# This workflow comes from https://github.com/ofek/hatch-mypyc +# https://github.com/ofek/hatch-mypyc/blob/5a198c0ba8660494d02716cfc9d79ce4adfb1442/.github/workflows/test.yml +name: Test / hpc_ai + +on: + schedule: + - cron: "0 0 * * *" + pull_request: + paths: + - "integrations/hpc_ai/**" + - "!integrations/hpc_ai/*.md" + - ".github/workflows/hpc_ai.yml" + push: + branches: + - main + paths: + - "integrations/hpc_ai/**" + - "!integrations/hpc_ai/*.md" + - ".github/workflows/hpc_ai.yml" + +defaults: + run: + working-directory: integrations/hpc_ai + +concurrency: + group: hpc_ai-${{ github.head_ref || github.sha }} + cancel-in-progress: true + +env: + PYTHONUNBUFFERED: "1" + FORCE_COLOR: "1" + HPC_AI_API_KEY: ${{ secrets.HPC_AI_API_KEY }} + TEST_MATRIX_OS: '["ubuntu-latest", "windows-latest", "macos-latest"]' + TEST_MATRIX_PYTHON: '["3.10", "3.14"]' + +jobs: + compute-test-matrix: + runs-on: ubuntu-slim + defaults: + run: + working-directory: . + outputs: + os: ${{ steps.set.outputs.os }} + python-version: ${{ steps.set.outputs.python-version }} + steps: + - id: set + run: | + echo 'os=${{ github.event_name == 'push' && '["ubuntu-latest"]' || env.TEST_MATRIX_OS }}' >> "$GITHUB_OUTPUT" + echo 'python-version=${{ github.event_name == 'push' && '["3.10"]' || env.TEST_MATRIX_PYTHON }}' >> "$GITHUB_OUTPUT" + + run: + name: Python ${{ matrix.python-version }} on ${{ startsWith(matrix.os, 'macos-') && 'macOS' || startsWith(matrix.os, 'windows-') && 'Windows' || 'Linux' }} + needs: compute-test-matrix + permissions: + contents: write + pull-requests: write + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: ${{ fromJSON(needs.compute-test-matrix.outputs.os) }} + python-version: ${{ fromJSON(needs.compute-test-matrix.outputs.python-version) }} + + steps: + - name: Support longpaths + if: matrix.os == 'windows-latest' + working-directory: . + run: git config --system core.longpaths true + + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: ${{ matrix.python-version }} + + - name: Install Hatch + run: pip install hatch + + - name: Lint + if: matrix.python-version == '3.10' && runner.os == 'Linux' + run: hatch run fmt-check && hatch run test:types + + - name: Run unit tests + run: hatch run test:unit-cov-retry + + # On PR: generates coverage comment artifact. On push to main: stores coverage baseline on data branch. + - name: Store unit tests coverage + if: matrix.python-version == '3.10' && runner.os == 'Linux' && github.event_name != 'schedule' + uses: py-cov-action/python-coverage-comment-action@7188638f871f721a365d644f505d1ff3df20d683 # v3.40 + with: + GITHUB_TOKEN: ${{ github.token }} + COVERAGE_PATH: integrations/hpc_ai + SUBPROJECT_ID: hpc_ai + COMMENT_ARTIFACT_NAME: coverage-comment-hpc_ai + MINIMUM_GREEN: 90 + MINIMUM_ORANGE: 60 + + - name: Run integration tests + run: hatch run test:integration-cov-append-retry + + - name: Store combined coverage + if: github.event_name == 'push' + uses: py-cov-action/python-coverage-comment-action@7188638f871f721a365d644f505d1ff3df20d683 # v3.40 + with: + GITHUB_TOKEN: ${{ github.token }} + COVERAGE_PATH: integrations/hpc_ai + SUBPROJECT_ID: hpc_ai-combined + COMMENT_ARTIFACT_NAME: coverage-comment-hpc_ai-combined + MINIMUM_GREEN: 90 + MINIMUM_ORANGE: 60 + + - name: Run unit tests with lowest direct dependencies + if: github.event_name != 'push' + run: | + hatch run uv pip compile pyproject.toml --resolution lowest-direct --output-file requirements_lowest_direct.txt + hatch -e test env run -- uv pip install -r requirements_lowest_direct.txt + hatch run test:unit + + # Since this integration inherits from OpenAIChatGenerator, we run ALL tests with Haystack main branch to catch regressions + - name: Nightly - run tests with Haystack main branch + if: github.event_name == 'schedule' + run: | + hatch env prune + hatch -e test env run -- uv pip install git+https://github.com/deepset-ai/haystack.git@main + hatch run test:unit-cov-retry + hatch run test:integration-cov-append-retry + + notify-slack-on-failure: + needs: run + if: failure() && github.event_name == 'schedule' + runs-on: ubuntu-slim + steps: + - uses: deepset-ai/notify-slack-action@3cda73b77a148f16f703274198e7771340cf862b # v1 + with: + slack-webhook-url: ${{ secrets.SLACK_WEBHOOK_URL_NOTIFICATIONS }} diff --git a/README.md b/README.md index 6d9a1c63b7..351a422738 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,7 @@ Please check out our [Contribution Guidelines](CONTRIBUTING.md) for all the deta | [google-genai-haystack](integrations/google_genai/) | Embedder, Generator | [![PyPI - Version](https://img.shields.io/pypi/v/google-genai-haystack.svg)](https://pypi.org/project/google-genai-haystack) | [![Test / google-genai](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/google_genai.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/google_genai.yml) | [![Coverage badge](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/deepset-ai/haystack-core-integrations/python-coverage-comment-action-data-google_genai/endpoint.json&label=)](https://htmlpreview.github.io/?https://github.com/deepset-ai/haystack-core-integrations/blob/python-coverage-comment-action-data-google_genai/htmlcov/index.html) | [![Coverage badge](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/deepset-ai/haystack-core-integrations/python-coverage-comment-action-data-google_genai-combined/endpoint.json&label=)](https://htmlpreview.github.io/?https://github.com/deepset-ai/haystack-core-integrations/blob/python-coverage-comment-action-data-google_genai-combined/htmlcov/index.html) | | [google-vertex-haystack](integrations/google_vertex/) | Embedder, Generator | [![PyPI - Version](https://img.shields.io/pypi/v/google-vertex-haystack.svg)](https://pypi.org/project/google-vertex-haystack) | **Archived** - use [google-genai-haystack](https://pypi.org/project/google-genai-haystack) instead | | | | [hanlp-haystack](integrations/hanlp/) | Preprocessor | [![PyPI - Version](https://img.shields.io/pypi/v/hanlp-haystack.svg)](https://pypi.org/project/hanlp-haystack) | [![Test / hanlp](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/hanlp.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/hanlp.yml) | [![Coverage badge](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/deepset-ai/haystack-core-integrations/python-coverage-comment-action-data-hanlp/endpoint.json&label=)](https://htmlpreview.github.io/?https://github.com/deepset-ai/haystack-core-integrations/blob/python-coverage-comment-action-data-hanlp/htmlcov/index.html) | [![Coverage badge](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/deepset-ai/haystack-core-integrations/python-coverage-comment-action-data-hanlp-combined/endpoint.json&label=)](https://htmlpreview.github.io/?https://github.com/deepset-ai/haystack-core-integrations/blob/python-coverage-comment-action-data-hanlp-combined/htmlcov/index.html) | +| [hpc-ai-haystack](integrations/hpc_ai/) | Generator | [![PyPI - Version](https://img.shields.io/pypi/v/hpc-ai-haystack.svg)](https://pypi.org/project/hpc-ai-haystack) | [![Test / hpc_ai](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/hpc_ai.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/hpc_ai.yml) | [![Coverage badge](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/deepset-ai/haystack-core-integrations/python-coverage-comment-action-data-hpc_ai/endpoint.json&label=)](https://htmlpreview.github.io/?https://github.com/deepset-ai/haystack-core-integrations/blob/python-coverage-comment-action-data-hpc_ai/htmlcov/index.html) | [![Coverage badge](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/deepset-ai/haystack-core-integrations/python-coverage-comment-action-data-hpc_ai-combined/endpoint.json&label=)](https://htmlpreview.github.io/?https://github.com/deepset-ai/haystack-core-integrations/blob/python-coverage-comment-action-data-hpc_ai-combined/htmlcov/index.html) | | [jina-haystack](integrations/jina/) | Connector, Embedder, Ranker | [![PyPI - Version](https://img.shields.io/pypi/v/jina-haystack.svg)](https://pypi.org/project/jina-haystack) | [![Test / jina](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/jina.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/jina.yml) | [![Coverage badge](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/deepset-ai/haystack-core-integrations/python-coverage-comment-action-data-jina/endpoint.json&label=)](https://htmlpreview.github.io/?https://github.com/deepset-ai/haystack-core-integrations/blob/python-coverage-comment-action-data-jina/htmlcov/index.html) | [![Coverage badge](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/deepset-ai/haystack-core-integrations/python-coverage-comment-action-data-jina-combined/endpoint.json&label=)](https://htmlpreview.github.io/?https://github.com/deepset-ai/haystack-core-integrations/blob/python-coverage-comment-action-data-jina-combined/htmlcov/index.html) | | [kreuzberg-haystack](integrations/kreuzberg/) | Converter | [![PyPI - Version](https://img.shields.io/pypi/v/kreuzberg-haystack.svg)](https://pypi.org/project/kreuzberg-haystack) | [![Test / kreuzberg](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/kreuzberg.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/kreuzberg.yml) | [![Coverage badge](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/deepset-ai/haystack-core-integrations/python-coverage-comment-action-data-kreuzberg/endpoint.json&label=)](https://htmlpreview.github.io/?https://github.com/deepset-ai/haystack-core-integrations/blob/python-coverage-comment-action-data-kreuzberg/htmlcov/index.html) | [![Coverage badge](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/deepset-ai/haystack-core-integrations/python-coverage-comment-action-data-kreuzberg-combined/endpoint.json&label=)](https://htmlpreview.github.io/?https://github.com/deepset-ai/haystack-core-integrations/blob/python-coverage-comment-action-data-kreuzberg-combined/htmlcov/index.html) | | [langfuse-haystack](integrations/langfuse/) | Tracer | [![PyPI - Version](https://img.shields.io/pypi/v/langfuse-haystack.svg?color=orange)](https://pypi.org/project/langfuse-haystack) | [![Test / langfuse](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/langfuse.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/langfuse.yml) | [![Coverage badge](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/deepset-ai/haystack-core-integrations/python-coverage-comment-action-data-langfuse/endpoint.json&label=)](https://htmlpreview.github.io/?https://github.com/deepset-ai/haystack-core-integrations/blob/python-coverage-comment-action-data-langfuse/htmlcov/index.html) | [![Coverage badge](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/deepset-ai/haystack-core-integrations/python-coverage-comment-action-data-langfuse-combined/endpoint.json&label=)](https://htmlpreview.github.io/?https://github.com/deepset-ai/haystack-core-integrations/blob/python-coverage-comment-action-data-langfuse-combined/htmlcov/index.html) | diff --git a/integrations/hpc_ai/CHANGELOG.md b/integrations/hpc_ai/CHANGELOG.md new file mode 100644 index 0000000000..522f6d5d8b --- /dev/null +++ b/integrations/hpc_ai/CHANGELOG.md @@ -0,0 +1,3 @@ +# Changelog + + diff --git a/integrations/hpc_ai/LICENSE.txt b/integrations/hpc_ai/LICENSE.txt new file mode 100644 index 0000000000..18efc6a014 --- /dev/null +++ b/integrations/hpc_ai/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 2025 AI/ML API + +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/hpc_ai/README.md b/integrations/hpc_ai/README.md new file mode 100644 index 0000000000..0ded58e8b3 --- /dev/null +++ b/integrations/hpc_ai/README.md @@ -0,0 +1,18 @@ +# hpc-ai-haystack + +[![PyPI - Version](https://img.shields.io/pypi/v/hpc-ai-haystack.svg)](https://pypi.org/project/hpc-ai-haystack) +[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/hpc-ai-haystack.svg)](https://pypi.org/project/hpc-ai-haystack) + +- [Integration page](https://haystack.deepset.ai/integrations/hpc-ai) +- [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/hpc_ai/CHANGELOG.md) + +--- + +## Contributing + +Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md). + +To run integration tests locally, export: + +- `HPC_AI_API_KEY` +- `HPC_AI_BASE_URL` (optional, defaults to `https://api.hpc-ai.com/inference/v1`) diff --git a/integrations/hpc_ai/examples/hpc_ai_basic_example.py b/integrations/hpc_ai/examples/hpc_ai_basic_example.py new file mode 100644 index 0000000000..828d6d6897 --- /dev/null +++ b/integrations/hpc_ai/examples/hpc_ai_basic_example.py @@ -0,0 +1,30 @@ +# SPDX-FileCopyrightText: 2023-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +# ruff: noqa: T201 + +"""Basic text generation example using HPCAIChatGenerator.""" + +from haystack.dataclasses import ChatMessage + +from haystack_integrations.components.generators.hpc_ai import HPCAIChatGenerator + + +def main() -> None: + """Generate a response without using any tools.""" + + generator = HPCAIChatGenerator() + + messages = [ + ChatMessage.from_system("You are a concise assistant."), + ChatMessage.from_user("Briefly explain what HPC-AI offers."), + ] + + reply = generator.run(messages=messages)["replies"][0] + + print(f"assistant response: {reply.text}") + + +if __name__ == "__main__": + main() diff --git a/integrations/hpc_ai/examples/hpc_ai_with_tools_example.py b/integrations/hpc_ai/examples/hpc_ai_with_tools_example.py new file mode 100644 index 0000000000..6a177dc167 --- /dev/null +++ b/integrations/hpc_ai/examples/hpc_ai_with_tools_example.py @@ -0,0 +1,77 @@ +# SPDX-FileCopyrightText: 2023-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +# ruff: noqa: T201 + +"""Run HPC-AI chat generation with tool calling and execution.""" + +from haystack.components.tools import ToolInvoker +from haystack.dataclasses import ChatMessage +from haystack.tools import Tool + +from haystack_integrations.components.generators.hpc_ai import HPCAIChatGenerator + + +def weather(city: str) -> str: + """Return mock weather info for the given city.""" + + return f"The weather in {city} is sunny and 32°C" + + +def main() -> None: + """Demonstrate calling a tool and feeding the result back to HPC-AI.""" + + tool_parameters = { + "type": "object", + "properties": {"city": {"type": "string"}}, + "required": ["city"], + } + + weather_tool = Tool( + name="weather", + description="Useful for getting the weather in a specific city", + parameters=tool_parameters, + function=weather, + ) + + tool_invoker = ToolInvoker(tools=[weather_tool]) + + client = HPCAIChatGenerator(model="moonshotai/kimi-k2.5") + + messages = [ + ChatMessage.from_system("You help users by calling the provided tools when they are relevant."), + ChatMessage.from_user("What's the weather in Tokyo today?"), + ] + + print("Requesting a tool call from the model...") + tool_request = client.run( + messages=messages, + tools=[weather_tool], + generation_kwargs={"tool_choice": {"type": "function", "function": {"name": "weather"}}}, + )["replies"][0] + + print(f"assistant tool request: {tool_request}") + + if not tool_request.tool_calls: + print("No tool call was produced by the model.") + return + + tool_messages = tool_invoker.run(messages=[tool_request])["tool_messages"] + for tool_message in tool_messages: + for tool_result in tool_message.tool_call_results: + print(f"tool output: {tool_result.result}") + + follow_up_messages = [*messages, tool_request, *tool_messages] + + final_reply = client.run( + messages=follow_up_messages, + tools=[weather_tool], + generation_kwargs={"tool_choice": "none"}, + )["replies"][0] + + print(f"assistant final answer: {final_reply.text}") + + +if __name__ == "__main__": + main() diff --git a/integrations/hpc_ai/pydoc/config_docusaurus.yml b/integrations/hpc_ai/pydoc/config_docusaurus.yml new file mode 100644 index 0000000000..ee6bbead3d --- /dev/null +++ b/integrations/hpc_ai/pydoc/config_docusaurus.yml @@ -0,0 +1,13 @@ +loaders: + - modules: + - haystack_integrations.components.generators.hpc_ai.chat.chat_generator + search_path: [../src] +processors: + - type: filter + documented_only: true + skip_empty_modules: true +renderer: + description: HPC-AI integration for Haystack + id: integrations-hpc-ai + filename: hpc_ai.md + title: HPC-AI diff --git a/integrations/hpc_ai/pyproject.toml b/integrations/hpc_ai/pyproject.toml new file mode 100644 index 0000000000..f5bff9f1fa --- /dev/null +++ b/integrations/hpc_ai/pyproject.toml @@ -0,0 +1,162 @@ +[build-system] +requires = ["hatchling", "hatch-vcs"] +build-backend = "hatchling.build" + +[project] +name = "hpc-ai-haystack" +dynamic = ["version"] +description = "HPC-AI integration for Haystack" +readme = "README.md" +requires-python = ">=3.10" +license = "Apache-2.0" +keywords = ["haystack", "hpc-ai", "llm", "openai-compatible"] +authors = [{ name = "deepset GmbH", email = "info@deepset.ai" }] +classifiers = [ + "License :: OSI Approved :: Apache Software License", + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", +] +dependencies = ["haystack-ai>=2.22.0"] + +[project.urls] +Documentation = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/hpc_ai#readme" +Issues = "https://github.com/deepset-ai/haystack-core-integrations/issues" +Source = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/hpc_ai" + +[tool.hatch.build.targets.wheel] +packages = ["src/haystack_integrations"] + +[tool.hatch.version] +source = "vcs" +tag-pattern = 'integrations\/hpc_ai-v(?P.*)' + +[tool.hatch.version.raw-options] +root = "../.." +git_describe_command = 'git describe --tags --match="integrations/hpc_ai-v[0-9]*"' + +[tool.hatch.envs.default] +installer = "uv" +dependencies = ["haystack-pydoc-tools", "ruff"] +[tool.hatch.envs.default.scripts] +docs = ["haystack-pydoc pydoc/config_docusaurus.yml"] +fmt = "ruff check --fix {args}; ruff format {args}" +fmt-check = "ruff check {args} && ruff format --check {args}" + +[tool.hatch.envs.test] +dependencies = [ + "pytest", + "pytest-asyncio", + "pytest-cov", + "pytest-rerunfailures", + "mypy", + "pip", + "pytz" +] + +[tool.hatch.envs.test.scripts] +unit = 'pytest -m "not integration" {args:tests}' +integration = 'pytest -m "integration" {args:tests}' +all = 'pytest {args:tests}' +unit-cov-retry = 'pytest --cov=haystack_integrations --reruns 3 --reruns-delay 30 -x -m "not integration" {args:tests}' +integration-cov-append-retry = 'pytest --cov=haystack_integrations --cov-append --reruns 3 --reruns-delay 30 -x -m "integration" {args:tests}' + +types = "mypy -p haystack_integrations.components.generators.hpc_ai {args}" + +[tool.mypy] +install_types = true +non_interactive = true +check_untyped_defs = true +disallow_incomplete_defs = true + + +[tool.ruff] +line-length = 120 + +[tool.ruff.lint] +select = [ + "A", + "ANN", + "ARG", + "B", + "C", + "D102", # Missing docstring in public method + "D103", # Missing docstring in public function + "D205", # 1 blank line required between summary line and description + "D209", # Closing triple quotes go to new line + "D213", # summary lines must be positioned on the second physical line of the docstring + "D417", # Missing argument descriptions in the docstring + "D419", # Docstring is empty + "DTZ", + "E", + "EM", + "F", + "I", + "ICN", + "ISC", + "N", + "PLC", + "PLE", + "PLR", + "PLW", + "Q", + "RUF", + "S", + "T", + "TID", + "UP", + "W", + "YTT", +] +ignore = [ + # Allow non-abstract empty methods in abstract base classes + "B027", + # Ignore checks for possible passwords + "S105", + "S106", + "S107", + # Ignore complexity + "C901", + "PLR0911", + "PLR0912", + "PLR0913", + "PLR0915", + # Misc + "B008", + "S101", +] + +[tool.ruff.lint.isort] +known-first-party = ["haystack_integrations"] + +[tool.ruff.lint.flake8-tidy-imports] +ban-relative-imports = "parents" + +[tool.ruff.lint.per-file-ignores] +# Tests can use magic values, assertions, and relative imports +"tests/**/*" = ["PLR2004", "S101", "TID252", "D", "ANN"] + +[tool.coverage.run] +source = ["haystack_integrations"] +branch = true +relative_files = true +parallel = false + + +[tool.coverage.report] +omit = ["*/tests/*", "*/__init__.py"] +show_missing = true +exclude_lines = ["no cov", "if __name__ == .__main__.:", "if TYPE_CHECKING:"] + +[tool.pytest.ini_options] +addopts = "--strict-markers" +markers = [ + "integration: integration tests", +] +log_cli = true diff --git a/integrations/hpc_ai/src/haystack_integrations/components/generators/hpc_ai/__init__.py b/integrations/hpc_ai/src/haystack_integrations/components/generators/hpc_ai/__init__.py new file mode 100644 index 0000000000..cf73b5e27e --- /dev/null +++ b/integrations/hpc_ai/src/haystack_integrations/components/generators/hpc_ai/__init__.py @@ -0,0 +1,3 @@ +from .chat.chat_generator import HPCAIChatGenerator + +__all__ = ["HPCAIChatGenerator"] diff --git a/integrations/hpc_ai/src/haystack_integrations/components/generators/hpc_ai/chat/__init__.py b/integrations/hpc_ai/src/haystack_integrations/components/generators/hpc_ai/chat/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/integrations/hpc_ai/src/haystack_integrations/components/generators/hpc_ai/chat/chat_generator.py b/integrations/hpc_ai/src/haystack_integrations/components/generators/hpc_ai/chat/chat_generator.py new file mode 100644 index 0000000000..a899a9f004 --- /dev/null +++ b/integrations/hpc_ai/src/haystack_integrations/components/generators/hpc_ai/chat/chat_generator.py @@ -0,0 +1,173 @@ +# SPDX-FileCopyrightText: 2023-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import os +from typing import Any, ClassVar + +from haystack import component, default_to_dict +from haystack.components.generators.chat import OpenAIChatGenerator +from haystack.dataclasses import ChatMessage, StreamingCallbackT +from haystack.tools import ( + ToolsType, + _check_duplicate_tool_names, + flatten_tools_or_toolsets, + serialize_tools_or_toolset, +) +from haystack.utils import serialize_callable +from haystack.utils.auth import Secret + +DEFAULT_API_BASE_URL = "https://api.hpc-ai.com/inference/v1" + + +@component +class HPCAIChatGenerator(OpenAIChatGenerator): + """ + Enables chat completion using HPC-AI's OpenAI-compatible API. + + HPC-AI exposes an OpenAI-compatible `/chat/completions` endpoint, so this component + reuses the standard OpenAI chat payload shape and response handling from Haystack's + `OpenAIChatGenerator`. + + You can pass any chat completion parameters supported by HPC-AI directly through + `generation_kwargs` during initialization or when calling `run`. + """ + + SUPPORTED_MODELS: ClassVar[list[str]] = [ + "minimax/minimax-m2.5", + "moonshotai/kimi-k2.5", + ] + """The HPC-AI models officially supported by this integration.""" + + def __init__( + self, + *, + api_key: Secret = Secret.from_env_var("HPC_AI_API_KEY"), + model: str = "minimax/minimax-m2.5", + streaming_callback: StreamingCallbackT | None = None, + api_base_url: str | None = None, + generation_kwargs: dict[str, Any] | None = None, + tools: ToolsType | None = None, + timeout: float | None = None, + extra_headers: dict[str, Any] | None = None, + max_retries: int | None = None, + http_client_kwargs: dict[str, Any] | None = None, + ) -> None: + """ + Creates an instance of `HPCAIChatGenerator`. + + :param api_key: + The HPC-AI API key. + :param model: + The HPC-AI chat completion model to use. + :param streaming_callback: + A callback function that is called when a new token is received from the stream. + :param api_base_url: + The HPC-AI API base URL. If not provided, the component reads `HPC_AI_BASE_URL` + and falls back to `https://api.hpc-ai.com/inference/v1`. + :param generation_kwargs: + Additional parameters forwarded directly to the HPC-AI chat completion endpoint. + :param tools: + A list of tools or a Toolset for which the model can prepare calls. + :param timeout: + The timeout for the HPC-AI API call. + :param extra_headers: + Additional HTTP headers to include in requests to the HPC-AI API. + :param max_retries: + Maximum number of retries to contact HPC-AI after an internal error. + If not set, it defaults to either the `OPENAI_MAX_RETRIES` environment variable, or 5. + :param http_client_kwargs: + Keyword arguments to configure a custom `httpx.Client` or `httpx.AsyncClient`. + """ + api_base_url = api_base_url or os.getenv("HPC_AI_BASE_URL", DEFAULT_API_BASE_URL) + + super(HPCAIChatGenerator, self).__init__( # noqa: UP008 + api_key=api_key, + model=model, + streaming_callback=streaming_callback, + api_base_url=api_base_url, + generation_kwargs=generation_kwargs, + tools=tools, + timeout=timeout, + max_retries=max_retries, + http_client_kwargs=http_client_kwargs, + ) + self.extra_headers = extra_headers + + 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, + api_base_url=self.api_base_url, + generation_kwargs=self.generation_kwargs, + api_key=self.api_key.to_dict(), + tools=serialize_tools_or_toolset(self.tools), + extra_headers=self.extra_headers, + timeout=self.timeout, + max_retries=self.max_retries, + http_client_kwargs=self.http_client_kwargs, + ) + + def _prepare_api_call( + self, + *, + messages: list[ChatMessage], + streaming_callback: StreamingCallbackT | None = None, + generation_kwargs: dict[str, Any] | None = None, + tools: ToolsType | None = None, + tools_strict: bool | None = None, + ) -> dict[str, Any]: + generation_kwargs = {**self.generation_kwargs, **(generation_kwargs or {})} + extra_headers = {**(self.extra_headers or {})} + + openai_formatted_messages: list[dict[str, Any]] = [message.to_openai_dict_format() for message in messages] + + tools_strict = tools_strict if tools_strict is not None else self.tools_strict + flattened_tools = flatten_tools_or_toolsets(tools or self.tools) + _check_duplicate_tool_names(flattened_tools) + + openai_tools = {} + if flattened_tools: + tool_definitions = [] + for tool in flattened_tools: + function_spec = {**tool.tool_spec} + if tools_strict: + function_spec["strict"] = True + parameters = function_spec.get("parameters") + if isinstance(parameters, dict): + parameters["additionalProperties"] = False + tool_definitions.append({"type": "function", "function": function_spec}) + openai_tools = {"tools": tool_definitions} + + is_streaming = streaming_callback is not None + num_responses = generation_kwargs.pop("n", 1) + + if is_streaming and num_responses > 1: + msg = "Cannot stream multiple responses, please set n=1." + raise ValueError(msg) + + response_format = generation_kwargs.pop("response_format", None) + base_args = { + "model": self.model, + "messages": openai_formatted_messages, + "n": num_responses, + **openai_tools, + "extra_body": {**generation_kwargs}, + "extra_headers": {**extra_headers}, + } + if response_format and not is_streaming: + return {**base_args, "response_format": response_format, "openai_endpoint": "parse"} + + final_args = {**base_args, "stream": is_streaming, "openai_endpoint": "create"} + if response_format: + final_args["response_format"] = response_format + return final_args diff --git a/integrations/hpc_ai/src/haystack_integrations/components/generators/py.typed b/integrations/hpc_ai/src/haystack_integrations/components/generators/py.typed new file mode 100644 index 0000000000..e69de29bb2 diff --git a/integrations/hpc_ai/tests/__init__.py b/integrations/hpc_ai/tests/__init__.py new file mode 100644 index 0000000000..6b5e14dc19 --- /dev/null +++ b/integrations/hpc_ai/tests/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2024-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/integrations/hpc_ai/tests/test_hpc_ai_chat_generator.py b/integrations/hpc_ai/tests/test_hpc_ai_chat_generator.py new file mode 100644 index 0000000000..df9b852120 --- /dev/null +++ b/integrations/hpc_ai/tests/test_hpc_ai_chat_generator.py @@ -0,0 +1,887 @@ +import os +from datetime import datetime +from unittest.mock import patch + +import pytest +import pytz +from haystack import Pipeline +from haystack.components.generators.utils import print_streaming_chunk +from haystack.components.tools import ToolInvoker +from haystack.dataclasses import ChatMessage, ChatRole, StreamingChunk, ToolCall +from haystack.tools import Tool +from haystack.utils.auth import Secret +from openai import OpenAIError +from openai.types.chat import ChatCompletion, ChatCompletionChunk, ChatCompletionMessage +from openai.types.chat.chat_completion import Choice +from openai.types.chat.chat_completion_chunk import Choice as ChoiceChunk +from openai.types.chat.chat_completion_chunk import ChoiceDelta, ChoiceDeltaToolCall, ChoiceDeltaToolCallFunction +from openai.types.completion_usage import CompletionTokensDetails, CompletionUsage, PromptTokensDetails + +from haystack_integrations.components.generators.hpc_ai.chat.chat_generator import HPCAIChatGenerator + + +class CollectorCallback: + """ + Callback to collect streaming chunks for testing purposes. + """ + + def __init__(self): + self.chunks = [] + + def __call__(self, chunk: StreamingChunk) -> None: + self.chunks.append(chunk) + + +@pytest.fixture +def chat_messages(): + return [ + ChatMessage.from_system("You are a helpful assistant"), + ChatMessage.from_user("What's the capital of France"), + ] + + +def weather(city: str): + """Get weather for a given city.""" + return f"The weather in {city} is sunny and 32°C" + + +@pytest.fixture +def tools(): + tool_parameters = {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]} + tool = Tool( + name="weather", + description="useful to determine the weather in a given location", + parameters=tool_parameters, + function=weather, + ) + + return [tool] + + +@pytest.fixture +def mock_chat_completion(): + """ + Mock the HPC-AI API completion response and reuse it for tests + """ + with patch("openai.resources.chat.completions.Completions.create") as mock_chat_completion_create: + completion = ChatCompletion( + id="foo", + model="minimax/minimax-m2.5", + object="chat.completion", + choices=[ + Choice( + finish_reason="stop", + logprobs=None, + index=0, + message=ChatCompletionMessage(content="Hello world!", role="assistant"), + ) + ], + created=int(datetime.now(tz=pytz.timezone("UTC")).timestamp()), + usage={"prompt_tokens": 57, "completion_tokens": 40, "total_tokens": 97}, + ) + + mock_chat_completion_create.return_value = completion + yield mock_chat_completion_create + + +class TestHPCAIChatGenerator: + def test_init_default(self, monkeypatch): + monkeypatch.setenv("HPC_AI_API_KEY", "test-api-key") + component = HPCAIChatGenerator() + assert component.client.api_key == "test-api-key" + assert component.model == "minimax/minimax-m2.5" + assert component.api_base_url == "https://api.hpc-ai.com/inference/v1" + assert component.streaming_callback is None + assert not component.generation_kwargs + + def test_init_default_uses_base_url_env(self, monkeypatch): + monkeypatch.setenv("HPC_AI_API_KEY", "test-api-key") + monkeypatch.setenv("HPC_AI_BASE_URL", "https://custom.hpc-ai.test/v1") + + component = HPCAIChatGenerator() + + assert component.api_base_url == "https://custom.hpc-ai.test/v1" + + def test_supported_models(self): + assert HPCAIChatGenerator.SUPPORTED_MODELS == [ + "minimax/minimax-m2.5", + "moonshotai/kimi-k2.5", + ] + + def test_init_fail_wo_api_key(self, monkeypatch): + monkeypatch.delenv("HPC_AI_API_KEY", raising=False) + with pytest.raises(ValueError, match=r"None of the .* environment variables are set"): + HPCAIChatGenerator() + + def test_init_with_parameters(self): + component = HPCAIChatGenerator( + api_key=Secret.from_token("test-api-key"), + model="minimax/minimax-m2.5", + streaming_callback=print_streaming_chunk, + api_base_url="test-base-url", + generation_kwargs={"max_tokens": 10, "some_test_param": "test-params"}, + ) + assert component.client.api_key == "test-api-key" + assert component.model == "minimax/minimax-m2.5" + 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("HPC_AI_API_KEY", "test-api-key") + component = HPCAIChatGenerator() + data = component.to_dict() + + assert ( + data["type"] == "haystack_integrations.components.generators.hpc_ai.chat.chat_generator.HPCAIChatGenerator" + ) + + expected_params = { + "api_key": {"env_vars": ["HPC_AI_API_KEY"], "strict": True, "type": "env_var"}, + "model": "minimax/minimax-m2.5", + "streaming_callback": None, + "api_base_url": "https://api.hpc-ai.com/inference/v1", + "generation_kwargs": {}, + "extra_headers": None, + "timeout": None, + "max_retries": None, + "tools": None, + "http_client_kwargs": None, + } + + for key, value in expected_params.items(): + assert data["init_parameters"][key] == value + + def test_to_dict_with_parameters(self, monkeypatch): + monkeypatch.setenv("ENV_VAR", "test-api-key") + component = HPCAIChatGenerator( + api_key=Secret.from_env_var("ENV_VAR"), + model="minimax/minimax-m2.5", + streaming_callback=print_streaming_chunk, + api_base_url="test-base-url", + generation_kwargs={"max_tokens": 10, "some_test_param": "test-params"}, + extra_headers={"test-header": "test-value"}, + timeout=10, + max_retries=10, + tools=None, + http_client_kwargs={"proxy": "http://localhost:8080"}, + ) + data = component.to_dict() + + assert ( + data["type"] == "haystack_integrations.components.generators.hpc_ai.chat.chat_generator.HPCAIChatGenerator" + ) + + expected_params = { + "api_key": {"env_vars": ["ENV_VAR"], "strict": True, "type": "env_var"}, + "model": "minimax/minimax-m2.5", + "api_base_url": "test-base-url", + "streaming_callback": "haystack.components.generators.utils.print_streaming_chunk", + "generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"}, + "extra_headers": {"test-header": "test-value"}, + "timeout": 10, + "max_retries": 10, + "tools": None, + "http_client_kwargs": {"proxy": "http://localhost:8080"}, + } + + for key, value in expected_params.items(): + assert data["init_parameters"][key] == value + + def test_from_dict(self, monkeypatch): + monkeypatch.setenv("HPC_AI_API_KEY", "fake-api-key") + data = { + "type": ("haystack_integrations.components.generators.hpc_ai.chat.chat_generator.HPCAIChatGenerator"), + "init_parameters": { + "api_key": {"env_vars": ["HPC_AI_API_KEY"], "strict": True, "type": "env_var"}, + "model": "minimax/minimax-m2.5", + "api_base_url": "test-base-url", + "streaming_callback": "haystack.components.generators.utils.print_streaming_chunk", + "generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"}, + "extra_headers": {"test-header": "test-value"}, + "timeout": 10, + "max_retries": 10, + "tools": None, + "http_client_kwargs": {"proxy": "http://localhost:8080"}, + }, + } + component = HPCAIChatGenerator.from_dict(data) + assert component.model == "minimax/minimax-m2.5" + assert component.streaming_callback is print_streaming_chunk + assert component.api_base_url == "test-base-url" + assert component.generation_kwargs == {"max_tokens": 10, "some_test_param": "test-params"} + assert component.api_key == Secret.from_env_var("HPC_AI_API_KEY") + assert component.http_client_kwargs == {"proxy": "http://localhost:8080"} + assert component.tools is None + assert component.extra_headers == {"test-header": "test-value"} + assert component.timeout == 10 + assert component.max_retries == 10 + + def test_from_dict_fail_wo_env_var(self, monkeypatch): + monkeypatch.delenv("HPC_AI_API_KEY", raising=False) + data = { + "type": ("haystack_integrations.components.generators.hpc_ai.chat.chat_generator.HPCAIChatGenerator"), + "init_parameters": { + "api_key": {"env_vars": ["HPC_AI_API_KEY"], "strict": True, "type": "env_var"}, + "model": "minimax/minimax-m2.5", + "api_base_url": "test-base-url", + "streaming_callback": "haystack.components.generators.utils.print_streaming_chunk", + "generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"}, + "extra_headers": {"test-header": "test-value"}, + "timeout": 10, + "max_retries": 10, + }, + } + with pytest.raises(ValueError, match=r"None of the .* environment variables are set"): + HPCAIChatGenerator.from_dict(data) + + def test_run(self, chat_messages, mock_chat_completion, monkeypatch): # noqa: ARG002 + monkeypatch.setenv("HPC_AI_API_KEY", "fake-api-key") + component = HPCAIChatGenerator() + 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, monkeypatch): + monkeypatch.setenv("HPC_AI_API_KEY", "fake-api-key") + component = HPCAIChatGenerator(generation_kwargs={"max_tokens": 10, "temperature": 0.5}) + response = component.run(chat_messages) + + # check that the component calls the HPC-AI API with the correct parameters + # for HPC-AI, these are passed in the extra_body parameter + _, kwargs = mock_chat_completion.call_args + assert kwargs["extra_body"]["max_tokens"] == 10 + assert kwargs["extra_body"]["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("HPC_AI_API_KEY", None), + reason="Export an env var called HPC_AI_API_KEY containing the HPC-AI API key to run this test.", + ) + @pytest.mark.integration + def test_live_run(self): + chat_messages = [ChatMessage.from_user("What's the capital of France")] + component = HPCAIChatGenerator(model="moonshotai/kimi-k2.5") + results = component.run(chat_messages) + assert len(results["replies"]) == 1 + message: ChatMessage = results["replies"][0] + assert message.text + assert "Paris" in message.text + assert "kimi-k2.5" in message.meta["model"] + assert message.meta["finish_reason"] == "stop" + + @pytest.mark.skipif( + not os.environ.get("HPC_AI_API_KEY", None), + reason="Export an env var called HPC_AI_API_KEY containing the HPC-AI API key to run this test.", + ) + @pytest.mark.integration + def test_live_run_wrong_model(self, chat_messages): + component = HPCAIChatGenerator(model="something-obviously-wrong") + with pytest.raises(OpenAIError): + component.run(chat_messages) + + @pytest.mark.skipif( + not os.environ.get("HPC_AI_API_KEY", None), + reason="Export an env var called HPC_AI_API_KEY containing the HPC-AI API key to run this test.", + ) + @pytest.mark.integration + def test_live_run_streaming(self): + class Callback: + def __init__(self): + self.responses = "" + self.counter = 0 + + def __call__(self, chunk: StreamingChunk) -> None: + self.counter += 1 + self.responses += chunk.content if chunk.content else "" + + callback = Callback() + component = HPCAIChatGenerator(streaming_callback=callback, model="moonshotai/kimi-k2.5") + results = component.run([ChatMessage.from_user("What's the capital of France?")]) + + assert len(results["replies"]) == 1 + message: ChatMessage = results["replies"][0] + assert message.text + assert "Paris" in message.text + + assert "kimi-k2.5" in message.meta["model"] + assert message.meta["finish_reason"] == "stop" + + assert callback.counter > 1 + assert "Paris" in callback.responses + + @pytest.mark.skipif( + not os.environ.get("HPC_AI_API_KEY", None), + reason="Export an env var called HPC_AI_API_KEY containing the HPC-AI API key to run this test.", + ) + @pytest.mark.integration + def test_live_run_with_tools(self, tools): + chat_messages = [ChatMessage.from_user("What's the weather like in Paris?")] + component = HPCAIChatGenerator(model="moonshotai/kimi-k2.5", tools=tools) + results = component.run(chat_messages) + assert len(results["replies"]) == 1 + message = results["replies"][0] + assert message.text is None or message.text == "" + + assert message.tool_calls + tool_call = message.tool_call + assert isinstance(tool_call, ToolCall) + assert tool_call.tool_name == "weather" + assert tool_call.arguments == {"city": "Paris"} + assert message.meta["finish_reason"] == "tool_calls" + + @pytest.mark.skipif( + not os.environ.get("HPC_AI_API_KEY", None), + reason="Export an env var called HPC_AI_API_KEY containing the HPC-AI API key to run this test.", + ) + @pytest.mark.integration + def test_live_run_with_tools_and_response(self, tools): + """ + Integration test that the HPCAIChatGenerator component can run with tools and get a response. + """ + initial_messages = [ChatMessage.from_user("What's the weather like in Paris and Berlin?")] + component = HPCAIChatGenerator(tools=tools, model="moonshotai/kimi-k2.5") + results = component.run(messages=initial_messages, generation_kwargs={"tool_choice": "auto"}) + + assert len(results["replies"]) == 1 + + # Find the message with tool calls + tool_message = results["replies"][0] + + assert isinstance(tool_message, ChatMessage) + tool_calls = tool_message.tool_calls + assert len(tool_calls) == 2 + assert ChatMessage.is_from(tool_message, ChatRole.ASSISTANT) + + for tool_call in tool_calls: + assert tool_call.id is not None + assert isinstance(tool_call, ToolCall) + assert tool_call.tool_name == "weather" + + arguments = [tool_call.arguments for tool_call in tool_calls] + assert sorted(arguments, key=lambda x: x["city"]) == [{"city": "Berlin"}, {"city": "Paris"}] + assert tool_message.meta["finish_reason"] == "tool_calls" + + new_messages = [ + initial_messages[0], + tool_message, + ChatMessage.from_tool(tool_result="22° C and sunny", origin=tool_calls[0]), + ChatMessage.from_tool(tool_result="16° C and windy", origin=tool_calls[1]), + ] + # Pass the tool result to the model to get the final response + results = component.run(new_messages) + + assert len(results["replies"]) == 1 + final_message = results["replies"][0] + assert final_message.is_from(ChatRole.ASSISTANT) + assert len(final_message.text) > 0 + assert "paris" in final_message.text.lower() + + @pytest.mark.skipif( + not os.environ.get("HPC_AI_API_KEY", None), + reason="Export an env var called HPC_AI_API_KEY containing the HPC-AI API key to run this test.", + ) + @pytest.mark.integration + def test_live_run_with_tools_streaming(self, tools): + """ + Integration test that the HPCAIChatGenerator component can run with tools and streaming. + """ + component = HPCAIChatGenerator( + tools=tools, streaming_callback=print_streaming_chunk, model="moonshotai/kimi-k2.5" + ) + results = component.run( + [ChatMessage.from_user("What's the weather like in Paris and Berlin?")], + generation_kwargs={"tool_choice": "auto"}, + ) + + assert len(results["replies"]) == 1 + + # Find the message with tool calls + tool_message = results["replies"][0] + + assert isinstance(tool_message, ChatMessage) + tool_calls = tool_message.tool_calls + assert len(tool_calls) == 2 + assert ChatMessage.is_from(tool_message, ChatRole.ASSISTANT) + + for tool_call in tool_calls: + assert tool_call.id is not None + assert isinstance(tool_call, ToolCall) + assert tool_call.tool_name == "weather" + + arguments = [tool_call.arguments for tool_call in tool_calls] + assert sorted(arguments, key=lambda x: x["city"]) == [{"city": "Berlin"}, {"city": "Paris"}] + assert tool_message.meta["finish_reason"] == "tool_calls" + + @pytest.mark.skipif( + not os.environ.get("HPC_AI_API_KEY", None), + reason="Export an env var called HPC_AI_API_KEY containing the HPC-AI API key to run this test.", + ) + @pytest.mark.integration + def test_pipeline_with_hpc_ai_chat_generator(self, tools): + """ + Test that the HPCAIChatGenerator component can be used in a pipeline + """ + pipeline = Pipeline() + pipeline.add_component("generator", HPCAIChatGenerator(tools=tools, model="moonshotai/kimi-k2.5")) + pipeline.add_component("tool_invoker", ToolInvoker(tools=tools)) + + pipeline.connect("generator", "tool_invoker") + + results = pipeline.run( + data={ + "generator": { + "messages": [ChatMessage.from_user("What's the weather like in Paris?")], + "generation_kwargs": {"tool_choice": "auto"}, + } + } + ) + + assert ( + "The weather in Paris is sunny and 32°C" + == results["tool_invoker"]["tool_messages"][0].tool_call_result.result + ) + + def test_serde_in_pipeline(self, monkeypatch): + """ + Test serialization/deserialization of HPCAIChatGenerator in a Pipeline, + including YAML conversion and detailed dictionary validation + """ + # Set mock API key + monkeypatch.setenv("HPC_AI_API_KEY", "test-key") + + # Create a test tool + tool = Tool( + name="weather", + description="useful to determine the weather in a given location", + parameters={"city": {"type": "string"}}, + function=weather, + ) + + # Create generator with specific configuration + generator = HPCAIChatGenerator( + model="minimax/minimax-m2.5", + generation_kwargs={"temperature": 0.7}, + streaming_callback=print_streaming_chunk, + tools=[tool], + ) + + # Create and configure pipeline + pipeline = Pipeline() + pipeline.add_component("generator", generator) + + # Get pipeline dictionary and verify its structure + pipeline_dict = pipeline.to_dict() + expected_dict = { + "metadata": {}, + "max_runs_per_component": 100, + "connection_type_validation": True, + "components": { + "generator": { + "type": "haystack_integrations.components.generators.hpc_ai.chat.chat_generator.HPCAIChatGenerator", + "init_parameters": { + "api_key": {"type": "env_var", "env_vars": ["HPC_AI_API_KEY"], "strict": True}, + "model": "minimax/minimax-m2.5", + "streaming_callback": "haystack.components.generators.utils.print_streaming_chunk", + "api_base_url": "https://api.hpc-ai.com/inference/v1", + "generation_kwargs": {"temperature": 0.7}, + "tools": [ + { + "type": "haystack.tools.tool.Tool", + "data": { + "name": "weather", + "description": "useful to determine the weather in a given location", + "parameters": {"city": {"type": "string"}}, + "function": "tests.test_hpc_ai_chat_generator.weather", + }, + } + ], + "http_client_kwargs": None, + "extra_headers": None, + "timeout": None, + "max_retries": None, + }, + } + }, + "connections": [], + } + + if not hasattr(pipeline, "_connection_type_validation"): + expected_dict.pop("connection_type_validation") + + # add outputs_to_string, inputs_from_state and outputs_to_state tool parameters for compatibility with + # haystack-ai>=2.12.0 + if hasattr(tool, "outputs_to_string"): + expected_dict["components"]["generator"]["init_parameters"]["tools"][0]["data"]["outputs_to_string"] = ( + tool.outputs_to_string + ) + if hasattr(tool, "inputs_from_state"): + expected_dict["components"]["generator"]["init_parameters"]["tools"][0]["data"]["inputs_from_state"] = ( + tool.inputs_from_state + ) + if hasattr(tool, "outputs_to_state"): + expected_dict["components"]["generator"]["init_parameters"]["tools"][0]["data"]["outputs_to_state"] = ( + tool.outputs_to_state + ) + + assert pipeline_dict == expected_dict + + # Test YAML serialization/deserialization + pipeline_yaml = pipeline.dumps() + new_pipeline = Pipeline.loads(pipeline_yaml) + assert new_pipeline == pipeline + + # Verify the loaded pipeline's generator has the same configuration + loaded_generator = new_pipeline.get_component("generator") + assert loaded_generator.model == generator.model + assert loaded_generator.generation_kwargs == generator.generation_kwargs + assert loaded_generator.streaming_callback == generator.streaming_callback + assert len(loaded_generator.tools) == len(generator.tools) + assert loaded_generator.tools[0].name == generator.tools[0].name + assert loaded_generator.tools[0].description == generator.tools[0].description + assert loaded_generator.tools[0].parameters == generator.tools[0].parameters + + +class TestChatCompletionChunkConversion: + def test_handle_stream_response(self): + hpc_ai_chunks = [ + ChatCompletionChunk( + id="gen-1750162525-tc7ParBHvsqd6rYhCDtK", + choices=[ + ChoiceChunk(delta=ChoiceDelta(content="", role="assistant"), index=0, native_finish_reason=None) + ], + created=1750162525, + model="minimax/minimax-m2.5", + object="chat.completion.chunk", + system_fingerprint="fp_34a54ae93c", + provider="OpenAI", + ), + ChatCompletionChunk( + id="gen-1750162525-tc7ParBHvsqd6rYhCDtK", + choices=[ + ChoiceChunk( + delta=ChoiceDelta( + role="assistant", + tool_calls=[ + ChoiceDeltaToolCall( + index=0, + id="call_zznlVyVfK0GJwY28SShJpDCh", + function=ChoiceDeltaToolCallFunction(arguments="", name="weather"), + type="function", + ) + ], + ), + index=0, + native_finish_reason=None, + ) + ], + created=1750162525, + model="minimax/minimax-m2.5", + object="chat.completion.chunk", + system_fingerprint="fp_34a54ae93c", + provider="OpenAI", + ), + ChatCompletionChunk( + id="gen-1750162525-tc7ParBHvsqd6rYhCDtK", + choices=[ + ChoiceChunk( + delta=ChoiceDelta( + role="assistant", + tool_calls=[ + ChoiceDeltaToolCall( + index=0, + function=ChoiceDeltaToolCallFunction(arguments='{"ci'), + type="function", + ) + ], + ), + index=0, + native_finish_reason=None, + ) + ], + created=1750162525, + model="minimax/minimax-m2.5", + object="chat.completion.chunk", + system_fingerprint="fp_34a54ae93c", + provider="OpenAI", + ), + ChatCompletionChunk( + id="gen-1750162525-tc7ParBHvsqd6rYhCDtK", + choices=[ + ChoiceChunk( + delta=ChoiceDelta( + role="assistant", + tool_calls=[ + ChoiceDeltaToolCall( + index=0, + function=ChoiceDeltaToolCallFunction(arguments='ty": '), + type="function", + ) + ], + ), + index=0, + native_finish_reason=None, + ) + ], + created=1750162525, + model="minimax/minimax-m2.5", + object="chat.completion.chunk", + system_fingerprint="fp_34a54ae93c", + provider="OpenAI", + ), + ChatCompletionChunk( + id="gen-1750162525-tc7ParBHvsqd6rYhCDtK", + choices=[ + ChoiceChunk( + delta=ChoiceDelta( + role="assistant", + tool_calls=[ + ChoiceDeltaToolCall( + index=0, + function=ChoiceDeltaToolCallFunction(arguments='"Paris'), + type="function", + ) + ], + ), + index=0, + native_finish_reason=None, + ) + ], + created=1750162525, + model="minimax/minimax-m2.5", + object="chat.completion.chunk", + system_fingerprint="fp_34a54ae93c", + provider="OpenAI", + ), + ChatCompletionChunk( + id="gen-1750162525-tc7ParBHvsqd6rYhCDtK", + choices=[ + ChoiceChunk( + delta=ChoiceDelta( + role="assistant", + tool_calls=[ + ChoiceDeltaToolCall( + index=0, + function=ChoiceDeltaToolCallFunction(arguments='"}'), + type="function", + ) + ], + ), + index=0, + native_finish_reason=None, + ) + ], + created=1750162525, + model="minimax/minimax-m2.5", + object="chat.completion.chunk", + system_fingerprint="fp_34a54ae93c", + provider="OpenAI", + ), + ChatCompletionChunk( + id="gen-1750162525-tc7ParBHvsqd6rYhCDtK", + choices=[ + ChoiceChunk( + delta=ChoiceDelta( + role="assistant", + tool_calls=[ + ChoiceDeltaToolCall( + index=1, + id="call_Mh1uOyW3Ys4gwydHjNHILHGX", + function=ChoiceDeltaToolCallFunction(arguments="", name="weather"), + type="function", + ) + ], + ), + index=0, + native_finish_reason=None, + ) + ], + created=1750162525, + model="minimax/minimax-m2.5", + object="chat.completion.chunk", + service_tier=None, + system_fingerprint="fp_34a54ae93c", + usage=None, + provider="OpenAI", + ), + ChatCompletionChunk( + id="gen-1750162525-tc7ParBHvsqd6rYhCDtK", + choices=[ + ChoiceChunk( + delta=ChoiceDelta( + role="assistant", + tool_calls=[ + ChoiceDeltaToolCall( + index=1, + id=None, + function=ChoiceDeltaToolCallFunction(arguments='{"ci'), + type="function", + ) + ], + ), + index=0, + native_finish_reason=None, + ) + ], + created=1750162525, + model="minimax/minimax-m2.5", + object="chat.completion.chunk", + system_fingerprint="fp_34a54ae93c", + provider="OpenAI", + ), + ChatCompletionChunk( + id="gen-1750162525-tc7ParBHvsqd6rYhCDtK", + choices=[ + ChoiceChunk( + delta=ChoiceDelta( + role="assistant", + tool_calls=[ + ChoiceDeltaToolCall( + index=1, + function=ChoiceDeltaToolCallFunction(arguments='ty": '), + type="function", + ) + ], + ), + index=0, + native_finish_reason=None, + ) + ], + created=1750162525, + model="minimax/minimax-m2.5", + object="chat.completion.chunk", + system_fingerprint="fp_34a54ae93c", + provider="OpenAI", + ), + ChatCompletionChunk( + id="gen-1750162525-tc7ParBHvsqd6rYhCDtK", + choices=[ + ChoiceChunk( + delta=ChoiceDelta( + role="assistant", + tool_calls=[ + ChoiceDeltaToolCall( + index=1, + function=ChoiceDeltaToolCallFunction(arguments='"Berli'), + type="function", + ) + ], + ), + index=0, + native_finish_reason=None, + ) + ], + created=1750162525, + model="minimax/minimax-m2.5", + object="chat.completion.chunk", + system_fingerprint="fp_34a54ae93c", + provider="OpenAI", + ), + ChatCompletionChunk( + id="gen-1750162525-tc7ParBHvsqd6rYhCDtK", + choices=[ + ChoiceChunk( + delta=ChoiceDelta( + role="assistant", + tool_calls=[ + ChoiceDeltaToolCall( + index=1, + function=ChoiceDeltaToolCallFunction(arguments='n"}'), + type="function", + ) + ], + ), + index=0, + native_finish_reason=None, + ) + ], + created=1750162525, + model="minimax/minimax-m2.5", + object="chat.completion.chunk", + system_fingerprint="fp_34a54ae93c", + provider="OpenAI", + ), + ChatCompletionChunk( + id="gen-1750162525-tc7ParBHvsqd6rYhCDtK", + choices=[ + ChoiceChunk( + delta=ChoiceDelta(content="", role="assistant"), + finish_reason="tool_calls", + index=0, + native_finish_reason="tool_calls", + ) + ], + created=1750162525, + model="minimax/minimax-m2.5", + object="chat.completion.chunk", + system_fingerprint="fp_34a54ae93c", + provider="OpenAI", + ), + ChatCompletionChunk( + id="gen-1750162525-tc7ParBHvsqd6rYhCDtK", + choices=[ + ChoiceChunk( + delta=ChoiceDelta(content="", role="assistant"), + index=0, + native_finish_reason=None, + ) + ], + created=1750162525, + model="minimax/minimax-m2.5", + object="chat.completion.chunk", + usage=CompletionUsage( + completion_tokens=42, + prompt_tokens=55, + total_tokens=97, + completion_tokens_details=CompletionTokensDetails(reasoning_tokens=0), + prompt_tokens_details=PromptTokensDetails(cached_tokens=0), + ), + provider="OpenAI", + ), + ] + + collector_callback = CollectorCallback() + llm = HPCAIChatGenerator(api_key=Secret.from_token("test-api-key")) + result = llm._handle_stream_response(hpc_ai_chunks, callback=collector_callback)[0] # type: ignore + + # Assert text is empty + assert result.text is None + + # Verify both tool calls were found and processed + assert len(result.tool_calls) == 2 + assert result.tool_calls[0].id == "call_zznlVyVfK0GJwY28SShJpDCh" + assert result.tool_calls[0].tool_name == "weather" + assert result.tool_calls[0].arguments == {"city": "Paris"} + assert result.tool_calls[1].id == "call_Mh1uOyW3Ys4gwydHjNHILHGX" + assert result.tool_calls[1].tool_name == "weather" + assert result.tool_calls[1].arguments == {"city": "Berlin"} + + # Verify meta information + assert result.meta["model"] == "minimax/minimax-m2.5" + assert result.meta["finish_reason"] == "tool_calls" + assert result.meta["index"] == 0 + assert result.meta["completion_start_time"] is not None + assert result.meta["usage"] == { + "completion_tokens": 42, + "prompt_tokens": 55, + "total_tokens": 97, + "completion_tokens_details": { + "accepted_prediction_tokens": None, + "audio_tokens": None, + "reasoning_tokens": 0, + "rejected_prediction_tokens": None, + }, + "prompt_tokens_details": { + "audio_tokens": None, + "cached_tokens": 0, + }, + } diff --git a/integrations/hpc_ai/tests/test_hpc_ai_chat_generator_async.py b/integrations/hpc_ai/tests/test_hpc_ai_chat_generator_async.py new file mode 100644 index 0000000000..00bfea934b --- /dev/null +++ b/integrations/hpc_ai/tests/test_hpc_ai_chat_generator_async.py @@ -0,0 +1,266 @@ +import os +from datetime import datetime +from unittest.mock import AsyncMock, patch + +import pytest +import pytz +from haystack.dataclasses import ( + ChatMessage, + ChatRole, + StreamingChunk, +) +from haystack.tools import Tool +from openai import AsyncOpenAI +from openai.types.chat import ChatCompletion, ChatCompletionMessage +from openai.types.chat.chat_completion import Choice + +from haystack_integrations.components.generators.hpc_ai.chat.chat_generator import ( + HPCAIChatGenerator, +) + + +@pytest.fixture +def chat_messages(): + return [ + ChatMessage.from_system("You are a helpful assistant"), + ChatMessage.from_user("What's the capital of France"), + ] + + +def weather(city: str): + """Get weather for a given city.""" + return f"The weather in {city} is sunny and 32°C" + + +@pytest.fixture +def tools(): + tool_parameters = { + "type": "object", + "properties": {"city": {"type": "string"}}, + "required": ["city"], + } + tool = Tool( + name="weather", + description="useful to determine the weather in a given location", + parameters=tool_parameters, + function=weather, + ) + + return [tool] + + +@pytest.fixture +def mock_async_chat_completion(): + """ + Mock the async HPC-AI API completion response and reuse it for async tests. + """ + with patch( + "openai.resources.chat.completions.AsyncCompletions.create", + new_callable=AsyncMock, + ) as mock_chat_completion_create: + completion = ChatCompletion( + id="foo", + model="minimax/minimax-m2.5", + object="chat.completion", + choices=[ + Choice( + finish_reason="stop", + logprobs=None, + index=0, + message=ChatCompletionMessage(content="Hello world!", role="assistant"), + ) + ], + created=int(datetime.now(tz=pytz.timezone("UTC")).timestamp()), + usage={ + "prompt_tokens": 57, + "completion_tokens": 40, + "total_tokens": 97, + }, + ) + # For async mocks, the return value should be awaitable + mock_chat_completion_create.return_value = completion + yield mock_chat_completion_create + + +class TestHPCAIChatGeneratorAsync: + def test_init_default_async(self, monkeypatch): + monkeypatch.setenv("HPC_AI_API_KEY", "test-api-key") + component = HPCAIChatGenerator() + + assert isinstance(component.async_client, AsyncOpenAI) + assert component.async_client.api_key == "test-api-key" + assert component.async_client.base_url == "https://api.hpc-ai.com/inference/v1/" + assert not component.generation_kwargs + + @pytest.mark.asyncio + async def test_run_async(self, chat_messages, mock_async_chat_completion, monkeypatch): # noqa: ARG002 + monkeypatch.setenv("HPC_AI_API_KEY", "fake-api-key") + component = HPCAIChatGenerator(model="moonshotai/kimi-k2.5") + response = await component.run_async(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"]] + + @pytest.mark.asyncio + async def test_run_async_with_params(self, chat_messages, mock_async_chat_completion, monkeypatch): + monkeypatch.setenv("HPC_AI_API_KEY", "fake-api-key") + component = HPCAIChatGenerator( + model="moonshotai/kimi-k2.5", generation_kwargs={"max_tokens": 10, "temperature": 0.5} + ) + response = await component.run_async(chat_messages) + + # check that the component calls the HPC-AI API with the correct parameters + _, kwargs = mock_async_chat_completion.call_args + assert kwargs["extra_body"]["max_tokens"] == 10 + assert kwargs["extra_body"]["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("HPC_AI_API_KEY", None), + reason="Export an env var called HPC_AI_API_KEY containing the HPC-AI API key to run this test.", + ) + @pytest.mark.integration + @pytest.mark.asyncio + async def test_live_run_async(self): + chat_messages = [ChatMessage.from_user("What's the capital of France")] + component = HPCAIChatGenerator(model="moonshotai/kimi-k2.5") + results = await component.run_async(chat_messages) + assert len(results["replies"]) == 1 + message: ChatMessage = results["replies"][0] + assert "Paris" in message.text + assert "kimi-k2.5" in message.meta["model"] + assert message.meta["finish_reason"] == "stop" + + @pytest.mark.skipif( + not os.environ.get("HPC_AI_API_KEY", None), + reason="Export an env var called HPC_AI_API_KEY containing the HPC-AI API key to run this test.", + ) + @pytest.mark.integration + @pytest.mark.asyncio + async def test_live_run_streaming_async(self): + counter = 0 + responses = "" + + async def callback(chunk: StreamingChunk): + nonlocal counter + nonlocal responses + counter += 1 + responses += chunk.content if chunk.content else "" + + component = HPCAIChatGenerator(streaming_callback=callback, model="moonshotai/kimi-k2.5") + results = await component.run_async([ChatMessage.from_user("What's the capital of France?")]) + + assert len(results["replies"]) == 1 + message: ChatMessage = results["replies"][0] + assert "Paris" in message.text + + assert "kimi-k2.5" in message.meta["model"] + assert message.meta["finish_reason"] == "stop" + + assert counter > 1 + assert "Paris" in responses + + @pytest.mark.skipif( + not os.environ.get("HPC_AI_API_KEY", None), + reason="Export an env var called HPC_AI_API_KEY containing the HPC-AI API key to run this test.", + ) + @pytest.mark.integration + @pytest.mark.asyncio + async def test_live_run_with_tools_and_response_async(self, tools): + """ + Integration test that the HPCAIChatGenerator component can run with tools and get a response. + """ + initial_messages = [ChatMessage.from_user("What's the weather like in Paris?")] + component = HPCAIChatGenerator(tools=tools, model="moonshotai/kimi-k2.5") + results = await component.run_async(messages=initial_messages, generation_kwargs={"tool_choice": "auto"}) + + assert len(results["replies"]) > 0, "No replies received" + + # Find the message with tool calls + tool_message = None + for message in results["replies"]: + if message.tool_call: + tool_message = message + break + + assert tool_message is not None, "No message with tool call found" + assert isinstance(tool_message, ChatMessage), "Tool message is not a ChatMessage instance" + assert ChatMessage.is_from(tool_message, ChatRole.ASSISTANT), "Tool message is not from the assistant" + + tool_call = tool_message.tool_call + assert tool_call.id, "Tool call does not contain value for 'id' key" + assert tool_call.tool_name == "weather" + assert tool_call.arguments == {"city": "Paris"} + assert tool_message.meta["finish_reason"] == "tool_calls" + + new_messages = [ + initial_messages[0], + tool_message, + ChatMessage.from_tool(tool_result="22° C", origin=tool_call), + ] + # Pass the tool result to the model to get the final response + results = await component.run_async(new_messages) + + assert len(results["replies"]) == 1 + final_message = results["replies"][0] + assert not final_message.tool_call + assert len(final_message.text) > 0 + assert "paris" in final_message.text.lower() + + @pytest.mark.skipif( + not os.environ.get("HPC_AI_API_KEY", None), + reason="Export an env var called HPC_AI_API_KEY containing the HPC-AI API key to run this test.", + ) + @pytest.mark.integration + @pytest.mark.asyncio + async def test_live_run_with_tools_streaming_async(self, tools): + """ + Integration test that the HPCAIChatGenerator component can run with tools and streaming. + """ + + counter = 0 + tool_calls = [] + + async def callback(chunk: StreamingChunk): + nonlocal counter + nonlocal tool_calls + counter += 1 + if chunk.meta.get("tool_calls"): + tool_calls.extend(chunk.meta["tool_calls"]) + + component = HPCAIChatGenerator(tools=tools, streaming_callback=callback, model="moonshotai/kimi-k2.5") + results = await component.run_async( + [ChatMessage.from_user("What's the weather like in Paris?")], + generation_kwargs={"tool_choice": "auto"}, + ) + + assert len(results["replies"]) > 0, "No replies received" + assert counter > 1, "Streaming callback was not called multiple times" + assert tool_calls, "No tool calls received in streaming" + + # Find the message with tool calls + tool_message = None + for message in results["replies"]: + if message.tool_call: + tool_message = message + break + + assert tool_message is not None, "No message with tool call found" + assert isinstance(tool_message, ChatMessage), "Tool message is not a ChatMessage instance" + assert ChatMessage.is_from(tool_message, ChatRole.ASSISTANT), "Tool message is not from the assistant" + + tool_call = tool_message.tool_call + assert tool_call.id, "Tool call does not contain value for 'id' key" + assert tool_call.tool_name == "weather" + assert tool_call.arguments == {"city": "Paris"} + assert tool_message.meta["finish_reason"] == "tool_calls"