-
Notifications
You must be signed in to change notification settings - Fork 808
Feature/add mistral generator #1135
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
jmartin-tech
merged 9 commits into
NVIDIA:main
from
dimensi0n:feature/mistral-generator
Apr 18, 2025
Merged
Changes from 7 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
3a65f1a
Create mistral generator and mistralai module
dimensi0n 0f97159
Clean requirements.txt because of pip freeze adding subpackages
dimensi0n ce9fc38
Define ENV_VAR and DEFAULT_PARAMS before __init__
dimensi0n bfd5709
Add backoff for rate limit exceptions and fix typo
dimensi0n 7d4c233
Add mockup test for mistral generator
dimensi0n 7f3cdda
Add empty doc file, remove unused test code and add mistralai to pypr…
dimensi0n fc99bd6
Add mock prompt test
dimensi0n 320f4a2
Use mockx decorator with mistral.json mock file instead of patch deco…
dimensi0n 89bb454
Remove useless api key enforcement & change backoff exception type
dimensi0n File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| garak.generators.mistral | ||
|
|
||
| .. automodule:: garak.generators.mistral | ||
| :members: | ||
| :undoc-members: | ||
| :show-inheritance: |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| DEFAULT_CLASS = "MistralGenerator" | ||
| import os | ||
| import backoff | ||
| from garak.generators.base import Generator | ||
| import garak._config as _config | ||
| from mistralai import Mistral | ||
| from garak import exception | ||
|
|
||
|
|
||
| class MistralGenerator(Generator): | ||
| """ | ||
| Interface for public endpoints of models hosted in Mistral La Plateforme (console.mistral.ai). | ||
| Expects API key in MISTRAL_API_TOKEN environment variable. | ||
| """ | ||
|
|
||
| generator_family_name = "mistral" | ||
| fullname = "Mistral AI" | ||
| supports_multiple_generations = False | ||
| ENV_VAR = "MISTRAL_API_KEY" | ||
| DEFAULT_PARAMS = Generator.DEFAULT_PARAMS | { | ||
| "name": "mistral-large-latest", | ||
| } | ||
|
|
||
| # avoid attempt to pickle the client attribute | ||
| def __getstate__(self) -> object: | ||
| self._clear_client() | ||
| return dict(self.__dict__) | ||
|
|
||
| # restore the client attribute | ||
| def __setstate__(self, d) -> object: | ||
| self.__dict__.update(d) | ||
| self._load_client() | ||
|
|
||
| def _load_client(self): | ||
| self.client = Mistral(api_key=self.api_key) | ||
|
|
||
| def _clear_client(self): | ||
| self.client = None | ||
|
|
||
| def __init__(self, name="", config_root=_config): | ||
| super().__init__(name, config_root) | ||
| if self.api_key is not None: | ||
| # ensure the token is in the expected runtime env var | ||
| os.environ[self.ENV_VAR] = self.api_key | ||
| self._load_client() | ||
|
|
||
| @backoff.on_exception(backoff.fibo, exception.RateLimitHit, max_value=70) | ||
dimensi0n marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| def _call_model(self, prompt, generations_this_call=1): | ||
dimensi0n marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| print(self.name) | ||
| chat_response = self.client.chat.complete( | ||
| model=self.name, | ||
| messages=[ | ||
| { | ||
| "role": "user", | ||
| "content": prompt, | ||
| }, | ||
| ], | ||
| ) | ||
| return [chat_response.choices[0].message.content] | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| import os | ||
| import pytest | ||
| from unittest.mock import patch | ||
| from garak.generators.mistral import MistralGenerator | ||
|
|
||
| DEFAULT_DEPLOYMENT_NAME = "mistral-small-latest" | ||
|
|
||
| @patch.dict(os.environ, {"MISTRAL_API_KEY": "fake_api_key"}) | ||
| @patch("garak.generators.mistral.MistralGenerator.generate") | ||
| def test_mistral_generator(mock_generate): | ||
| # Définir le retour simulé | ||
| mock_generate.return_value = ["Mocked response"] | ||
|
|
||
| # Initialiser le générateur | ||
| generator = MistralGenerator() | ||
|
|
||
| # Appeler la méthode générer | ||
| output = generator.generate("Test prompt") | ||
|
|
||
| # Vérifier que la fonction a bien été appelée | ||
| mock_generate.assert_called_once_with("Test prompt") | ||
|
|
||
| # Vérifier le résultat | ||
| assert output == ["Mocked response"] | ||
dimensi0n marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| @pytest.mark.skipif( | ||
| os.getenv(MistralGenerator.ENV_VAR, None) is None, | ||
| reason=f"Mistral API key is not set in {MistralGenerator.ENV_VAR}", | ||
| ) | ||
| def test_mistral_chat(): | ||
| generator = MistralGenerator(name=DEFAULT_DEPLOYMENT_NAME) | ||
| assert generator.name == DEFAULT_DEPLOYMENT_NAME | ||
| output = generator.generate("Hello Mistral!") | ||
| assert len(output) == 1 # expect 1 generation by default | ||
| print("test passed!") | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.