-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Support Mistral predicted outputs using Pydantic models #3372
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
TKaluza
wants to merge
7
commits into
pydantic:main
Choose a base branch
from
TKaluza:dev/mistral-predicted-outputs
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.
+167
−1
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
52420be
Add prediction support for MistralModel and associated tests.
TKaluza 71e3b82
Update tests and model documentation for revised Mistral prediction h…
TKaluza c2f2e3f
Add test for unsupported prediction types in MistralModel and fix min…
TKaluza 7dc5f87
Update test to expand pyright ignore rules for argument type enforcem…
TKaluza 2f6da17
Fix indentation in test for unsupported prediction types in MistralModel
TKaluza 2820f67
Add missing newline in test_mistral.py for readability in tests
TKaluza a6497eb
Merge branch 'main' into dev/mistral-predicted-outputs
DouweM 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 |
|---|---|---|
|
|
@@ -77,6 +77,10 @@ | |
| ) | ||
| from mistralai.models.assistantmessage import AssistantMessage as MistralAssistantMessage | ||
| from mistralai.models.function import Function as MistralFunction | ||
| from mistralai.models.prediction import ( | ||
| Prediction as MistralPrediction, | ||
| PredictionTypedDict as MistralPredictionTypedDict, | ||
| ) | ||
| from mistralai.models.systemmessage import SystemMessage as MistralSystemMessage | ||
| from mistralai.models.toolmessage import ToolMessage as MistralToolMessage | ||
| from mistralai.models.usermessage import UserMessage as MistralUserMessage | ||
|
|
@@ -114,8 +118,12 @@ class MistralModelSettings(ModelSettings, total=False): | |
| """Settings used for a Mistral model request.""" | ||
|
|
||
| # ALL FIELDS MUST BE `mistral_` PREFIXED SO YOU CAN MERGE THEM WITH OTHER MODELS. | ||
| mistral_prediction: str | MistralPrediction | MistralPredictionTypedDict | None | ||
| """Prediction content for the model to use as a prefix. See Predictive outputs. | ||
|
|
||
| # This class is a placeholder for any future mistral-specific settings | ||
| This feature is currently only supported for certain Mistral models. See the model cards at Models. | ||
| As of now, codestral-latest and mistral-large-2411 support [predicted outputs](https://docs.mistral.ai/capabilities/predicted_outputs). | ||
| """ | ||
|
|
||
|
|
||
| @dataclass(init=False) | ||
|
|
@@ -241,6 +249,7 @@ async def _completions_create( | |
| timeout_ms=self._get_timeout_ms(model_settings.get('timeout')), | ||
| random_seed=model_settings.get('seed', UNSET), | ||
| stop=model_settings.get('stop_sequences', None), | ||
| prediction=self._map_setting_prediction(model_settings.get('mistral_prediction', None)), | ||
| http_headers={'User-Agent': get_user_agent()}, | ||
| ) | ||
| except SDKError as e: | ||
|
|
@@ -281,6 +290,7 @@ async def _stream_completions_create( | |
| presence_penalty=model_settings.get('presence_penalty'), | ||
| frequency_penalty=model_settings.get('frequency_penalty'), | ||
| stop=model_settings.get('stop_sequences', None), | ||
| prediction=self._map_setting_prediction(model_settings.get('mistral_prediction', None)), | ||
| http_headers={'User-Agent': get_user_agent()}, | ||
| ) | ||
|
|
||
|
|
@@ -298,6 +308,7 @@ async def _stream_completions_create( | |
| 'type': 'json_object' | ||
| }, # TODO: Should be able to use json_schema now: https://docs.mistral.ai/capabilities/structured-output/custom_structured_output/, https://github.com/mistralai/client-python/blob/bc4adf335968c8a272e1ab7da8461c9943d8e701/src/mistralai/extra/utils/response_format.py#L9 | ||
| stream=True, | ||
| prediction=self._map_setting_prediction(model_settings.get('mistral_prediction', None)), | ||
| http_headers={'User-Agent': get_user_agent()}, | ||
| ) | ||
|
|
||
|
|
@@ -307,6 +318,7 @@ async def _stream_completions_create( | |
| model=str(self._model_name), | ||
| messages=mistral_messages, | ||
| stream=True, | ||
| prediction=self._map_setting_prediction(model_settings.get('mistral_prediction', None)), | ||
| http_headers={'User-Agent': get_user_agent()}, | ||
| ) | ||
| assert response, 'A unexpected empty response from Mistral.' | ||
|
|
@@ -427,6 +439,24 @@ def _map_tool_call(t: ToolCallPart) -> MistralToolCall: | |
| function=MistralFunctionCall(name=t.tool_name, arguments=t.args or {}), | ||
| ) | ||
|
|
||
| @staticmethod | ||
| def _map_setting_prediction( | ||
| prediction: str | MistralPredictionTypedDict | MistralPrediction | None, | ||
| ) -> MistralPrediction | None: | ||
| """Maps various prediction input types to a MistralPrediction object.""" | ||
| if not prediction: | ||
| return None | ||
| if isinstance(prediction, MistralPrediction): | ||
| return prediction | ||
| elif isinstance(prediction, str): | ||
| return MistralPrediction(content=prediction) | ||
| elif isinstance(prediction, dict): | ||
| return MistralPrediction.model_validate(prediction) | ||
| else: | ||
| raise RuntimeError( | ||
| f'Unsupported prediction type: {type(prediction)} for MistralModelSettings. Expected str, dict, or MistralPrediction.' | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. With the suggestion above this can be simplified a lot and we won't need this error anymore, but as a note for the future: we don't need errors like this, we can assume the user is type-checking their code. |
||
| ) | ||
|
|
||
| def _generate_user_output_format(self, schemas: list[dict[str, Any]]) -> MistralUserMessage: | ||
| """Get a message with an example of the expected output format.""" | ||
| examples: list[dict[str, Any]] = [] | ||
|
|
||
70 changes: 70 additions & 0 deletions
70
tests/models/cassettes/test_mistral/test_mistral_chat_with_prediction.yaml
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,70 @@ | ||
| interactions: | ||
| - request: | ||
| headers: | ||
| accept: | ||
| - application/json | ||
| accept-encoding: | ||
| - gzip, deflate | ||
| connection: | ||
| - keep-alive | ||
| content-length: | ||
| - '315' | ||
| content-type: | ||
| - application/json | ||
| host: | ||
| - api.mistral.ai | ||
| method: POST | ||
| parsed_body: | ||
| messages: | ||
| - content: | ||
| - text: Correct the math, keep everything else. No explanation, no formatting. | ||
| type: text | ||
| - text: The result of 21+21=99 | ||
| type: text | ||
| role: user | ||
| model: mistral-large-2411 | ||
| n: 1 | ||
| prediction: | ||
| content: The result of 21+21=99 | ||
| type: content | ||
| stream: false | ||
| top_p: 1.0 | ||
| uri: https://api.mistral.ai/v1/chat/completions | ||
| response: | ||
| headers: | ||
| access-control-allow-origin: | ||
| - '*' | ||
| alt-svc: | ||
| - h3=":443"; ma=86400 | ||
| connection: | ||
| - keep-alive | ||
| content-length: | ||
| - '319' | ||
| content-type: | ||
| - application/json | ||
| mistral-correlation-id: | ||
| - 019a63b7-40ba-70cb-94d0-84f036d7c76f | ||
| strict-transport-security: | ||
| - max-age=15552000; includeSubDomains; preload | ||
| transfer-encoding: | ||
| - chunked | ||
| parsed_body: | ||
| choices: | ||
| - finish_reason: stop | ||
| index: 0 | ||
| message: | ||
| content: The result of 21+21=42 | ||
| role: assistant | ||
| tool_calls: null | ||
| created: 1762609545 | ||
| id: 6c36e8b6c3c145bd8ada32f9bd0f6be9 | ||
| model: mistral-large-2411 | ||
| object: chat.completion | ||
| usage: | ||
| completion_tokens: 13 | ||
| prompt_tokens: 33 | ||
| total_tokens: 46 | ||
| status: | ||
| code: 200 | ||
| message: OK | ||
| version: 1 |
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
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could we support only
str? It looks like the types don't have any additional fields, andNoneis unnecessary as they key can just be omitted from the dict.Also if you're up for updating the OpenAI equivalent to support
stras well, that'd be great :)