-
Notifications
You must be signed in to change notification settings - Fork 19
feat(ChatMistral): Add Mistral support #145
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
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
80d8aba
Quick and dirty start on ChatMistral()
cpsievert dc7f87a
Update changelog
cpsievert 8eae584
Better handling of kwarg differences
cpsievert 19ed22e
Tool calling is known to be poorly supported
cpsievert b928add
Merge branch 'main' into feat/chat-mistral
cpsievert 1163608
Cleanup docs/tests
cpsievert 17d0f56
Add callout about known limitations
cpsievert 9a65723
fix: avoid error when structured data is in conversation history
cpsievert a66bc19
default model works better for the image tests
cpsievert 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
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,181 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import os | ||
| from typing import TYPE_CHECKING, Optional | ||
|
|
||
| from ._chat import Chat | ||
| from ._logging import log_model_default | ||
| from ._provider_openai import OpenAIProvider | ||
| from ._utils import MISSING, MISSING_TYPE, is_testing | ||
|
|
||
| if TYPE_CHECKING: | ||
| from openai.types.chat import ChatCompletion | ||
|
|
||
| from .types.openai import ChatClientArgs, SubmitInputArgs | ||
|
|
||
|
|
||
| def ChatMistral( | ||
| *, | ||
| system_prompt: Optional[str] = None, | ||
| model: Optional[str] = None, | ||
| api_key: Optional[str] = None, | ||
| base_url: str = "https://api.mistral.ai/v1/", | ||
| seed: int | None | MISSING_TYPE = MISSING, | ||
| kwargs: Optional["ChatClientArgs"] = None, | ||
| ) -> Chat["SubmitInputArgs", ChatCompletion]: | ||
| """ | ||
| Chat with a model hosted on Mistral's La Plateforme. | ||
|
|
||
| Mistral AI provides high-performance language models through their API platform. | ||
|
|
||
| Prerequisites | ||
| ------------- | ||
|
|
||
| ::: {.callout-note} | ||
| ## API credentials | ||
|
|
||
| Get your API key from https://console.mistral.ai/api-keys. | ||
| ::: | ||
|
|
||
| Examples | ||
| -------- | ||
| ```python | ||
| import os | ||
| from chatlas import ChatMistral | ||
|
|
||
| chat = ChatMistral(api_key=os.getenv("MISTRAL_API_KEY")) | ||
| chat.chat("Tell me three jokes about statisticians") | ||
| ``` | ||
|
|
||
| Known limitations | ||
| ----------------- | ||
|
|
||
| * Tool calling may be unstable. | ||
| * Images require a model that supports vision. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| system_prompt | ||
| A system prompt to set the behavior of the assistant. | ||
| model | ||
| The model to use for the chat. The default, None, will pick a reasonable | ||
| default, and warn you about it. We strongly recommend explicitly | ||
| choosing a model for all but the most casual use. | ||
| api_key | ||
| The API key to use for authentication. You generally should not supply | ||
| this directly, but instead set the `MISTRAL_API_KEY` environment | ||
| variable. | ||
| base_url | ||
| The base URL to the endpoint; the default uses Mistral AI. | ||
| seed | ||
| Optional integer seed that Mistral uses to try and make output more | ||
| reproducible. | ||
| kwargs | ||
| Additional arguments to pass to the `openai.OpenAI()` client | ||
| constructor (Mistral uses OpenAI-compatible API). | ||
|
|
||
| Returns | ||
| ------- | ||
| Chat | ||
| A chat object that retains the state of the conversation. | ||
|
|
||
| Note | ||
| ---- | ||
| Pasting an API key into a chat constructor (e.g., `ChatMistral(api_key="...")`) | ||
| is the simplest way to get started, and is fine for interactive use, but is | ||
| problematic for code that may be shared with others. | ||
|
|
||
| Instead, consider using environment variables or a configuration file to manage | ||
| your credentials. One popular way to manage credentials is to use a `.env` file | ||
| to store your credentials, and then use the `python-dotenv` package to load them | ||
| into your environment. | ||
|
|
||
| ```shell | ||
| pip install python-dotenv | ||
| ``` | ||
|
|
||
| ```shell | ||
| # .env | ||
| MISTRAL_API_KEY=... | ||
| ``` | ||
|
|
||
| ```python | ||
| from chatlas import ChatMistral | ||
| from dotenv import load_dotenv | ||
|
|
||
| load_dotenv() | ||
| chat = ChatMistral() | ||
| chat.console() | ||
| ``` | ||
|
|
||
| Another, more general, solution is to load your environment variables into the shell | ||
| before starting Python (maybe in a `.bashrc`, `.zshrc`, etc. file): | ||
|
|
||
| ```shell | ||
| export MISTRAL_API_KEY=... | ||
| ``` | ||
| """ | ||
| if isinstance(seed, MISSING_TYPE): | ||
| seed = 1014 if is_testing() else None | ||
|
|
||
| if model is None: | ||
| model = log_model_default("mistral-large-latest") | ||
|
|
||
| if api_key is None: | ||
| api_key = os.getenv("MISTRAL_API_KEY") | ||
|
|
||
| return Chat( | ||
| provider=MistralProvider( | ||
| api_key=api_key, | ||
| model=model, | ||
| base_url=base_url, | ||
| seed=seed, | ||
| kwargs=kwargs, | ||
| ), | ||
| system_prompt=system_prompt, | ||
| ) | ||
|
|
||
|
|
||
| class MistralProvider(OpenAIProvider): | ||
| def __init__( | ||
| self, | ||
| *, | ||
| api_key: Optional[str] = None, | ||
| model: str, | ||
| base_url: str = "https://api.mistral.ai/v1/", | ||
| seed: Optional[int] = None, | ||
| name: str = "Mistral", | ||
| kwargs: Optional["ChatClientArgs"] = None, | ||
| ): | ||
| super().__init__( | ||
| api_key=api_key, | ||
| model=model, | ||
| base_url=base_url, | ||
| seed=seed, | ||
| name=name, | ||
| kwargs=kwargs, | ||
| ) | ||
|
|
||
| # Mistral is essentially OpenAI-compatible, with a couple small differences. | ||
| # We _could_ bring in the Mistral SDK and use it directly for more precise typing, | ||
| # etc., but for now that doesn't seem worth it. | ||
| def _chat_perform_args( | ||
| self, stream, turns, tools, data_model=None, kwargs=None | ||
| ) -> "SubmitInputArgs": | ||
| # Get the base arguments from OpenAI provider | ||
| kwargs2 = super()._chat_perform_args(stream, turns, tools, data_model, kwargs) | ||
|
|
||
| # Mistral doesn't support stream_options | ||
| if "stream_options" in kwargs2: | ||
| del kwargs2["stream_options"] | ||
|
|
||
| # Mistral wants random_seed, not seed | ||
| if seed := kwargs2.pop("seed", None): | ||
| if isinstance(seed, int): | ||
| kwargs2["extra_body"] = {"random_seed": seed} | ||
| elif seed is not None: | ||
| raise ValueError( | ||
| "MistralProvider only accepts an integer seed, or None." | ||
| ) | ||
|
|
||
| return kwargs2 | ||
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
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,73 @@ | ||
| import os | ||
|
|
||
| import pytest | ||
|
|
||
| from chatlas import ChatMistral | ||
|
|
||
| from .conftest import ( | ||
| assert_data_extraction, | ||
| assert_images_inline, | ||
| assert_images_remote, | ||
| assert_turns_existing, | ||
| assert_turns_system, | ||
| ) | ||
|
|
||
| api_key = os.getenv("MISTRAL_API_KEY") | ||
| if api_key is None: | ||
| pytest.skip("MISTRAL_API_KEY is not set; skipping tests", allow_module_level=True) | ||
|
|
||
|
|
||
| def test_mistral_simple_request(): | ||
| chat = ChatMistral( | ||
| system_prompt="Be as terse as possible; no punctuation", | ||
| ) | ||
| chat.chat("What is 1 + 1?") | ||
| turn = chat.get_last_turn() | ||
| assert turn is not None | ||
| assert turn.tokens is not None | ||
| assert len(turn.tokens) == 3 | ||
| assert turn.tokens[0] > 0 # prompt tokens | ||
| assert turn.tokens[1] > 0 # completion tokens | ||
| assert turn.finish_reason == "stop" | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_mistral_simple_streaming_request(): | ||
| chat = ChatMistral( | ||
| system_prompt="Be as terse as possible; no punctuation", | ||
| ) | ||
| res = [] | ||
| async for x in await chat.stream_async("What is 1 + 1?"): | ||
| res.append(x) | ||
| assert "2" in "".join(res) | ||
| turn = chat.get_last_turn() | ||
| assert turn is not None | ||
| assert turn.finish_reason == "stop" | ||
|
|
||
|
|
||
| def test_mistral_respects_turns_interface(): | ||
| chat_fun = ChatMistral | ||
| assert_turns_system(chat_fun) | ||
| assert_turns_existing(chat_fun) | ||
|
|
||
|
|
||
| # Tool calling is poorly supported | ||
| # def test_mistral_tool_variations(): | ||
| # chat_fun = ChatMistral | ||
| # assert_tools_simple(chat_fun) | ||
| # assert_tools_simple_stream_content(chat_fun) | ||
|
|
||
| # Tool calling is poorly supported | ||
| # @pytest.mark.asyncio | ||
| # async def test_mistral_tool_variations_async(): | ||
| # await assert_tools_async(ChatMistral) | ||
|
|
||
|
|
||
| def test_data_extraction(): | ||
| assert_data_extraction(ChatMistral) | ||
|
|
||
|
|
||
| def test_mistral_images(): | ||
|
|
||
| assert_images_inline(ChatMistral) | ||
| assert_images_remote(ChatMistral) |
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.