-
Notifications
You must be signed in to change notification settings - Fork 318
Mistral Genie Support #274
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
Open
leonardocrociani
wants to merge
6
commits into
feyninc:main
Choose a base branch
from
leonardocrociani:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+101
−1
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
0763aed
mistral ai genie
leonardocrociani bdfa96d
dependency fix
leonardocrociani 544b924
Update src/chonkie/genie/mistral.py
leonardocrociani dc52626
Update src/chonkie/genie/mistral.py
leonardocrociani 6391973
Update src/chonkie/genie/mistral.py
leonardocrociani 2f0fc6a
Change chat method to chat.complete in mistral.py
leonardocrociani 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
Some comments aren't visible on the classic Files Changed page.
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
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,96 @@ | ||
| """Implementation of the MistralGenie class.""" | ||
| import importlib.util as importutil | ||
| import json | ||
| import os | ||
| from typing import TYPE_CHECKING, Any, Dict, Optional | ||
|
|
||
| from .base import BaseGenie | ||
|
|
||
| if TYPE_CHECKING: | ||
| from pydantic import BaseModel | ||
|
|
||
|
|
||
| class MistralGenie(BaseGenie): | ||
| """Mistral's Genie.""" | ||
|
|
||
| def __init__( | ||
| self, | ||
| model: str = "mistral-large-latest", | ||
| api_key: Optional[str] = None | ||
| ): | ||
| """Initialize the MistralGenie class. | ||
|
|
||
| Args: | ||
| model (str): The model to use. | ||
| api_key (Optional[str]): The API key to use. | ||
|
|
||
| """ | ||
| super().__init__() | ||
|
|
||
| # Lazily import the dependencies | ||
| self._import_dependencies() | ||
|
|
||
| # Initialize the API key | ||
| self.api_key = api_key or os.environ.get("MISTRAL_API_KEY") | ||
| if not self.api_key: | ||
| raise ValueError( | ||
| "MistralGenie requires an API key. Either pass the `api_key` " | ||
| "parameter or set the `MISTRAL_API_KEY` in your environment." | ||
| ) | ||
|
|
||
| # Initialize the client and model | ||
| self.client = MistralClient(api_key=self.api_key) # type: ignore | ||
| self.model = model | ||
|
|
||
| def generate(self, prompt: str) -> str: | ||
| """Generate a response based on the given prompt.""" | ||
| messages = [{"role": "user", "content": prompt}] | ||
| response = self.client.chat.complete(model=self.model, messages=messages) | ||
| return str(response.choices[0].message.content) | ||
|
|
||
| def generate_json(self, prompt: str, schema: "BaseModel") -> Dict[str, Any]: | ||
| """Generate a JSON response based on the given prompt and schema.""" | ||
| json_schema = json.dumps(schema.model_json_schema(), indent=2) | ||
| full_prompt = ( | ||
| f"{prompt}\n\n" | ||
| "Please provide the output in a JSON format that strictly adheres to the " | ||
| f"following schema:\n```json\n{json_schema}\n```" | ||
| ) | ||
| messages = [{"role": "user", "content": full_prompt}] | ||
|
|
||
| response = self.client.chat.complete( | ||
| model=self.model, | ||
| messages=messages, | ||
| response_format={"type": "json_object"}, | ||
| ) | ||
|
|
||
| try: | ||
| content = response.choices[0].message.content | ||
| return dict(json.loads(content)) | ||
| except json.JSONDecodeError as e: | ||
| raise ValueError(f"Failed to parse JSON response: {e}") | ||
|
|
||
| def _is_available(self) -> bool: | ||
| """Check if all the dependencies are available in the environment.""" | ||
| if ( | ||
| importutil.find_spec("pydantic") is not None | ||
| and importutil.find_spec("mistralai") is not None | ||
| ): | ||
| return True | ||
| return False | ||
|
leonardocrociani marked this conversation as resolved.
|
||
|
|
||
| def _import_dependencies(self) -> None: | ||
| """Import all the required dependencies.""" | ||
| if self._is_available(): | ||
| global BaseModel, MistralClient | ||
| from mistralai import Mistral as MistralClient | ||
| from pydantic import BaseModel | ||
| else: | ||
| raise ImportError( | ||
| "One or more of the required modules are not available: " | ||
| "[pydantic, mistralai]" | ||
| ) | ||
|
|
||
| def __repr__(self) -> str: | ||
| """Return a string representation of the MistralGenie instance.""" | ||
| return f"MistralGenie(model={self.model})" | ||
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.