diff --git a/.github/workflows/run_example_scripts.yaml b/.github/workflows/run_example_scripts.yaml index cecefb0e..4f82e0d7 100644 --- a/.github/workflows/run_example_scripts.yaml +++ b/.github/workflows/run_example_scripts.yaml @@ -47,5 +47,4 @@ jobs: uv pip install --system "$PACKAGE" ./scripts/run_examples.sh env: - MISTRAL_AGENT_ID: ${{ secrets.CI_AGENT_ID }} MISTRAL_API_KEY: ${{ env.MISTRAL_API_KEY }} diff --git a/.github/workflows/sdk_publish_mistralai_sdk.yaml b/.github/workflows/sdk_publish_mistralai_sdk.yaml index 0483de11..c3fdd9e0 100644 --- a/.github/workflows/sdk_publish_mistralai_sdk.yaml +++ b/.github/workflows/sdk_publish_mistralai_sdk.yaml @@ -6,6 +6,11 @@ permissions: statuses: write "on": workflow_dispatch: + inputs: + confirm_publish: + description: 'Type "publish" to confirm.' + required: false + type: string push: branches: - main @@ -14,7 +19,10 @@ permissions: - "*/RELEASES.md" jobs: publish: - if: github.ref == 'refs/heads/main' + # Auto-publish on push to main branch; require manual confirmation for workflow_dispatch + if: | + (github.event_name == 'push' && github.ref == 'refs/heads/main') || + (github.event_name == 'workflow_dispatch' && github.event.inputs.confirm_publish == 'publish') uses: speakeasy-api/sdk-generation-action/.github/workflows/sdk-publish.yaml@7951d9dce457425b900b2dd317253499d98c2587 # v15 secrets: github_access_token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore index cf2de5ee..7ead1d0d 100644 --- a/.gitignore +++ b/.gitignore @@ -5,7 +5,6 @@ **/.speakeasy/logs/ .vscode/ .speakeasy/reports -README-PYPI.md .venv/ pyrightconfig.json src/*.egg-info/ diff --git a/README-PYPI.md b/README-PYPI.md new file mode 100644 index 00000000..ac177f6b --- /dev/null +++ b/README-PYPI.md @@ -0,0 +1,1070 @@ +# Mistral Python Client + +## Migrating from v1 + +If you are upgrading from v1 to v2, check the [migration guide](https://github.com/mistralai/client-python/blob/main/MIGRATION.md) for details on breaking changes and how to update your code. + +## API Key Setup + +Before you begin, you will need a Mistral AI API key. + +1. Get your own Mistral API Key: +2. Set your Mistral API Key as an environment variable. You only need to do this once. + +```bash +# set Mistral API Key (using zsh for example) +$ echo 'export MISTRAL_API_KEY=[your_key_here]' >> ~/.zshenv + +# reload the environment (or just quit and open a new terminal) +$ source ~/.zshenv +``` + + +## Summary + +Mistral AI API: Our Chat Completion and Embeddings APIs specification. Create your account on [La Plateforme](https://console.mistral.ai) to get access and read the [docs](https://docs.mistral.ai) to learn how to use it. + + + +## Table of Contents + +* [Mistral Python Client](#mistral-python-client) + * [Migrating from v1](#migrating-from-v1) + * [API Key Setup](#api-key-setup) + * [SDK Installation](#sdk-installation) + * [SDK Example Usage](#sdk-example-usage) + * [Providers' SDKs Example Usage](#providers-sdks-example-usage) + * [Available Resources and Operations](#available-resources-and-operations) + * [Server-sent event streaming](#server-sent-event-streaming) + * [File uploads](#file-uploads) + * [Retries](#retries) + * [Error Handling](#error-handling) + * [Server Selection](#server-selection) + * [Custom HTTP Client](#custom-http-client) + * [Authentication](#authentication) + * [Resource Management](#resource-management) + * [Debugging](#debugging) + * [IDE Support](#ide-support) +* [Development](#development) + * [Contributions](#contributions) + + + + +## SDK Installation + +> [!NOTE] +> **Python version upgrade policy** +> +> Once a Python version reaches its [official end of life date](https://devguide.python.org/versions/), a 3-month grace period is provided for users to upgrade. Following this grace period, the minimum python version supported in the SDK will be updated. + +The SDK can be installed with *uv*, *pip*, or *poetry* package managers. + +### uv + +*uv* is a fast Python package installer and resolver, designed as a drop-in replacement for pip and pip-tools. It's recommended for its speed and modern Python tooling capabilities. + +```bash +uv add mistralai +``` + +### PIP + +*PIP* is the default package installer for Python, enabling easy installation and management of packages from PyPI via the command line. + +```bash +pip install mistralai +``` + +### Poetry + +*Poetry* is a modern tool that simplifies dependency management and package publishing by using a single `pyproject.toml` file to handle project metadata and dependencies. + +```bash +poetry add mistralai +``` + +### Shell and script usage with `uv` + +You can use this SDK in a Python shell with [uv](https://docs.astral.sh/uv/) and the `uvx` command that comes with it like so: + +```shell +uvx --from mistralai python +``` + +It's also possible to write a standalone Python script without needing to set up a whole project like so: + +```python +#!/usr/bin/env -S uv run --script +# /// script +# requires-python = ">=3.10" +# dependencies = [ +# "mistralai", +# ] +# /// + +from mistralai.client import Mistral + +sdk = Mistral( + # SDK arguments +) + +# Rest of script here... +``` + +Once that is saved to a file, you can run it with `uv run script.py` where +`script.py` can be replaced with the actual file name. + + +### Agents extra dependencies + +When using the agents related feature it is required to add the `agents` extra dependencies. This can be added when +installing the package: + +```bash +pip install "mistralai[agents]" +``` + +> Note: These features require Python 3.10+ (the SDK minimum). + +### Additional packages + +Additional `mistralai-*` packages (e.g. `mistralai-workflows`) can be installed separately and are available under the `mistralai` namespace: + +```bash +pip install mistralai-workflows +``` + + +## SDK Example Usage + +### Create Chat Completions + +This example shows how to create chat completions. + +```python +# Synchronous Example +from mistralai.client import Mistral +import os + + +with Mistral( + api_key=os.getenv("MISTRAL_API_KEY", ""), +) as mistral: + + res = mistral.chat.complete(model="mistral-large-latest", messages=[ + { + "role": "user", + "content": "Who is the best French painter? Answer in one short sentence.", + }, + ], stream=False, response_format={ + "type": "text", + }) + + # Handle response + print(res) +``` + +
+ +The same SDK client can also be used to make asynchronous requests by importing asyncio. + +```python +# Asynchronous Example +import asyncio +from mistralai.client import Mistral +import os + +async def main(): + + async with Mistral( + api_key=os.getenv("MISTRAL_API_KEY", ""), + ) as mistral: + + res = await mistral.chat.complete_async(model="mistral-large-latest", messages=[ + { + "role": "user", + "content": "Who is the best French painter? Answer in one short sentence.", + }, + ], stream=False, response_format={ + "type": "text", + }) + + # Handle response + print(res) + +asyncio.run(main()) +``` + +### Upload a file + +This example shows how to upload a file. + +```python +# Synchronous Example +from mistralai.client import Mistral +import os + + +with Mistral( + api_key=os.getenv("MISTRAL_API_KEY", ""), +) as mistral: + + res = mistral.files.upload(file={ + "file_name": "example.file", + "content": open("example.file", "rb"), + }, visibility="workspace") + + # Handle response + print(res) +``` + +
+ +The same SDK client can also be used to make asynchronous requests by importing asyncio. + +```python +# Asynchronous Example +import asyncio +from mistralai.client import Mistral +import os + +async def main(): + + async with Mistral( + api_key=os.getenv("MISTRAL_API_KEY", ""), + ) as mistral: + + res = await mistral.files.upload_async(file={ + "file_name": "example.file", + "content": open("example.file", "rb"), + }, visibility="workspace") + + # Handle response + print(res) + +asyncio.run(main()) +``` + +### Create Agents Completions + +This example shows how to create agents completions. + +```python +# Synchronous Example +from mistralai.client import Mistral +import os + + +with Mistral( + api_key=os.getenv("MISTRAL_API_KEY", ""), +) as mistral: + + res = mistral.agents.complete(messages=[ + { + "role": "user", + "content": "Who is the best French painter? Answer in one short sentence.", + }, + ], agent_id="", stream=False, response_format={ + "type": "text", + }) + + # Handle response + print(res) +``` + +
+ +The same SDK client can also be used to make asynchronous requests by importing asyncio. + +```python +# Asynchronous Example +import asyncio +from mistralai.client import Mistral +import os + +async def main(): + + async with Mistral( + api_key=os.getenv("MISTRAL_API_KEY", ""), + ) as mistral: + + res = await mistral.agents.complete_async(messages=[ + { + "role": "user", + "content": "Who is the best French painter? Answer in one short sentence.", + }, + ], agent_id="", stream=False, response_format={ + "type": "text", + }) + + # Handle response + print(res) + +asyncio.run(main()) +``` + +### Create Embedding Request + +This example shows how to create an embedding request. + +```python +# Synchronous Example +from mistralai.client import Mistral +import os + + +with Mistral( + api_key=os.getenv("MISTRAL_API_KEY", ""), +) as mistral: + + res = mistral.embeddings.create(model="mistral-embed", inputs=[ + "Embed this sentence.", + "As well as this one.", + ]) + + # Handle response + print(res) +``` + +
+ +The same SDK client can also be used to make asynchronous requests by importing asyncio. + +```python +# Asynchronous Example +import asyncio +from mistralai.client import Mistral +import os + +async def main(): + + async with Mistral( + api_key=os.getenv("MISTRAL_API_KEY", ""), + ) as mistral: + + res = await mistral.embeddings.create_async(model="mistral-embed", inputs=[ + "Embed this sentence.", + "As well as this one.", + ]) + + # Handle response + print(res) + +asyncio.run(main()) +``` + + + +### More examples + +You can run the examples in the `examples/` directory using `uv run`. + + +## Providers' SDKs Example Usage + +### Azure AI + +**Prerequisites** + +Before you begin, ensure you have `AZURE_ENDPOINT` and an `AZURE_API_KEY`. To obtain these, you will need to deploy Mistral on Azure AI. +See [instructions for deploying Mistral on Azure AI here](https://docs.mistral.ai/deployment/cloud/azure/). + +**Step 1: Install** + +```bash +pip install mistralai +``` + +**Step 2: Example Usage** + +Here's a basic example to get you started. You can also run [the example in the `examples` directory](https://github.com/mistralai/client-python/blob/main/examples/azure). + +```python +import os +from mistralai.azure.client import MistralAzure + +# The SDK automatically injects api-version as a query parameter +client = MistralAzure( + api_key=os.environ["AZURE_API_KEY"], + server_url=os.environ["AZURE_ENDPOINT"], + api_version="2024-05-01-preview", # Optional, this is the default +) + +res = client.chat.complete( + model=os.environ["AZURE_MODEL"], + messages=[ + { + "role": "user", + "content": "Hello there!", + } + ], +) +print(res.choices[0].message.content) +``` + +### Google Cloud + + +**Prerequisites** + +Before you begin, you will need to create a Google Cloud project and enable the Mistral API. To do this, follow the instructions [here](https://docs.mistral.ai/deployment/cloud/vertex/). + +To run this locally you will also need to ensure you are authenticated with Google Cloud. You can do this by running + +```bash +gcloud auth application-default login +``` + +**Step 1: Install** + +```bash +pip install mistralai +# For GCP authentication support (required): +pip install "mistralai[gcp]" +``` + +**Step 2: Example Usage** + +Here's a basic example to get you started. You can also run [the example in the `examples` directory](https://github.com/mistralai/client-python/blob/main/examples/gcp). + +The SDK automatically: +- Detects credentials via `google.auth.default()` +- Auto-refreshes tokens when they expire +- Builds the Vertex AI URL from `project_id` and `region` + +```python +import os +from mistralai.gcp.client import MistralGCP + +# The SDK auto-detects credentials and builds the Vertex AI URL +client = MistralGCP( + project_id=os.environ.get("GCP_PROJECT_ID"), # Optional: auto-detected from credentials + region="us-central1", # Default: europe-west4 +) + +res = client.chat.complete( + model="mistral-small-2503", + messages=[ + { + "role": "user", + "content": "Hello there!", + } + ], +) +print(res.choices[0].message.content) +``` + + + +## Available Resources and Operations + +
+Available methods + +### [Agents](https://github.com/mistralai/client-python/blob/main/docs/sdks/agents/README.md) + +* [complete](https://github.com/mistralai/client-python/blob/main/docs/sdks/agents/README.md#complete) - Agents Completion +* [stream](https://github.com/mistralai/client-python/blob/main/docs/sdks/agents/README.md#stream) - Stream Agents completion + +### [Audio.Transcriptions](https://github.com/mistralai/client-python/blob/main/docs/sdks/transcriptions/README.md) + +* [complete](https://github.com/mistralai/client-python/blob/main/docs/sdks/transcriptions/README.md#complete) - Create Transcription +* [stream](https://github.com/mistralai/client-python/blob/main/docs/sdks/transcriptions/README.md#stream) - Create Streaming Transcription (SSE) + +### [Batch.Jobs](https://github.com/mistralai/client-python/blob/main/docs/sdks/batchjobs/README.md) + +* [list](https://github.com/mistralai/client-python/blob/main/docs/sdks/batchjobs/README.md#list) - Get Batch Jobs +* [create](https://github.com/mistralai/client-python/blob/main/docs/sdks/batchjobs/README.md#create) - Create Batch Job +* [get](https://github.com/mistralai/client-python/blob/main/docs/sdks/batchjobs/README.md#get) - Get Batch Job +* [cancel](https://github.com/mistralai/client-python/blob/main/docs/sdks/batchjobs/README.md#cancel) - Cancel Batch Job + +### [Beta.Agents](https://github.com/mistralai/client-python/blob/main/docs/sdks/betaagents/README.md) + +* [create](https://github.com/mistralai/client-python/blob/main/docs/sdks/betaagents/README.md#create) - Create an agent that can be used within a conversation. +* [list](https://github.com/mistralai/client-python/blob/main/docs/sdks/betaagents/README.md#list) - List agent entities. +* [get](https://github.com/mistralai/client-python/blob/main/docs/sdks/betaagents/README.md#get) - Retrieve an agent entity. +* [update](https://github.com/mistralai/client-python/blob/main/docs/sdks/betaagents/README.md#update) - Update an agent entity. +* [delete](https://github.com/mistralai/client-python/blob/main/docs/sdks/betaagents/README.md#delete) - Delete an agent entity. +* [update_version](https://github.com/mistralai/client-python/blob/main/docs/sdks/betaagents/README.md#update_version) - Update an agent version. +* [list_versions](https://github.com/mistralai/client-python/blob/main/docs/sdks/betaagents/README.md#list_versions) - List all versions of an agent. +* [get_version](https://github.com/mistralai/client-python/blob/main/docs/sdks/betaagents/README.md#get_version) - Retrieve a specific version of an agent. +* [create_version_alias](https://github.com/mistralai/client-python/blob/main/docs/sdks/betaagents/README.md#create_version_alias) - Create or update an agent version alias. +* [list_version_aliases](https://github.com/mistralai/client-python/blob/main/docs/sdks/betaagents/README.md#list_version_aliases) - List all aliases for an agent. +* [delete_version_alias](https://github.com/mistralai/client-python/blob/main/docs/sdks/betaagents/README.md#delete_version_alias) - Delete an agent version alias. + +### [Beta.Connectors](https://github.com/mistralai/client-python/blob/main/docs/sdks/connectors/README.md) + +* [create](https://github.com/mistralai/client-python/blob/main/docs/sdks/connectors/README.md#create) - Create a new connector. +* [list](https://github.com/mistralai/client-python/blob/main/docs/sdks/connectors/README.md#list) - List all connectors. +* [call_tool](https://github.com/mistralai/client-python/blob/main/docs/sdks/connectors/README.md#call_tool) - Call Connector Tool +* [get](https://github.com/mistralai/client-python/blob/main/docs/sdks/connectors/README.md#get) - Get a connector. +* [update](https://github.com/mistralai/client-python/blob/main/docs/sdks/connectors/README.md#update) - Update a connector. +* [delete](https://github.com/mistralai/client-python/blob/main/docs/sdks/connectors/README.md#delete) - Delete a connector. + +### [Beta.Conversations](https://github.com/mistralai/client-python/blob/main/docs/sdks/conversations/README.md) + +* [start](https://github.com/mistralai/client-python/blob/main/docs/sdks/conversations/README.md#start) - Create a conversation and append entries to it. +* [list](https://github.com/mistralai/client-python/blob/main/docs/sdks/conversations/README.md#list) - List all created conversations. +* [get](https://github.com/mistralai/client-python/blob/main/docs/sdks/conversations/README.md#get) - Retrieve a conversation information. +* [delete](https://github.com/mistralai/client-python/blob/main/docs/sdks/conversations/README.md#delete) - Delete a conversation. +* [append](https://github.com/mistralai/client-python/blob/main/docs/sdks/conversations/README.md#append) - Append new entries to an existing conversation. +* [get_history](https://github.com/mistralai/client-python/blob/main/docs/sdks/conversations/README.md#get_history) - Retrieve all entries in a conversation. +* [get_messages](https://github.com/mistralai/client-python/blob/main/docs/sdks/conversations/README.md#get_messages) - Retrieve all messages in a conversation. +* [restart](https://github.com/mistralai/client-python/blob/main/docs/sdks/conversations/README.md#restart) - Restart a conversation starting from a given entry. +* [start_stream](https://github.com/mistralai/client-python/blob/main/docs/sdks/conversations/README.md#start_stream) - Create a conversation and append entries to it. +* [append_stream](https://github.com/mistralai/client-python/blob/main/docs/sdks/conversations/README.md#append_stream) - Append new entries to an existing conversation. +* [restart_stream](https://github.com/mistralai/client-python/blob/main/docs/sdks/conversations/README.md#restart_stream) - Restart a conversation starting from a given entry. + +### [Beta.Libraries](https://github.com/mistralai/client-python/blob/main/docs/sdks/libraries/README.md) + +* [list](https://github.com/mistralai/client-python/blob/main/docs/sdks/libraries/README.md#list) - List all libraries you have access to. +* [create](https://github.com/mistralai/client-python/blob/main/docs/sdks/libraries/README.md#create) - Create a new Library. +* [get](https://github.com/mistralai/client-python/blob/main/docs/sdks/libraries/README.md#get) - Detailed information about a specific Library. +* [delete](https://github.com/mistralai/client-python/blob/main/docs/sdks/libraries/README.md#delete) - Delete a library and all of its documents. +* [update](https://github.com/mistralai/client-python/blob/main/docs/sdks/libraries/README.md#update) - Update a library. + +#### [Beta.Libraries.Accesses](https://github.com/mistralai/client-python/blob/main/docs/sdks/accesses/README.md) + +* [list](https://github.com/mistralai/client-python/blob/main/docs/sdks/accesses/README.md#list) - List all of the access to this library. +* [update_or_create](https://github.com/mistralai/client-python/blob/main/docs/sdks/accesses/README.md#update_or_create) - Create or update an access level. +* [delete](https://github.com/mistralai/client-python/blob/main/docs/sdks/accesses/README.md#delete) - Delete an access level. + +#### [Beta.Libraries.Documents](https://github.com/mistralai/client-python/blob/main/docs/sdks/documents/README.md) + +* [list](https://github.com/mistralai/client-python/blob/main/docs/sdks/documents/README.md#list) - List documents in a given library. +* [upload](https://github.com/mistralai/client-python/blob/main/docs/sdks/documents/README.md#upload) - Upload a new document. +* [get](https://github.com/mistralai/client-python/blob/main/docs/sdks/documents/README.md#get) - Retrieve the metadata of a specific document. +* [update](https://github.com/mistralai/client-python/blob/main/docs/sdks/documents/README.md#update) - Update the metadata of a specific document. +* [delete](https://github.com/mistralai/client-python/blob/main/docs/sdks/documents/README.md#delete) - Delete a document. +* [text_content](https://github.com/mistralai/client-python/blob/main/docs/sdks/documents/README.md#text_content) - Retrieve the text content of a specific document. +* [status](https://github.com/mistralai/client-python/blob/main/docs/sdks/documents/README.md#status) - Retrieve the processing status of a specific document. +* [get_signed_url](https://github.com/mistralai/client-python/blob/main/docs/sdks/documents/README.md#get_signed_url) - Retrieve the signed URL of a specific document. +* [extracted_text_signed_url](https://github.com/mistralai/client-python/blob/main/docs/sdks/documents/README.md#extracted_text_signed_url) - Retrieve the signed URL of text extracted from a given document. +* [reprocess](https://github.com/mistralai/client-python/blob/main/docs/sdks/documents/README.md#reprocess) - Reprocess a document. + +### [Beta.Observability.Campaigns](https://github.com/mistralai/client-python/blob/main/docs/sdks/campaigns/README.md) + +* [create](https://github.com/mistralai/client-python/blob/main/docs/sdks/campaigns/README.md#create) - Create and start a new campaign +* [list](https://github.com/mistralai/client-python/blob/main/docs/sdks/campaigns/README.md#list) - Get all campaigns +* [fetch](https://github.com/mistralai/client-python/blob/main/docs/sdks/campaigns/README.md#fetch) - Get campaign by id +* [delete](https://github.com/mistralai/client-python/blob/main/docs/sdks/campaigns/README.md#delete) - Delete a campaign +* [fetch_status](https://github.com/mistralai/client-python/blob/main/docs/sdks/campaigns/README.md#fetch_status) - Get campaign status by campaign id +* [list_events](https://github.com/mistralai/client-python/blob/main/docs/sdks/campaigns/README.md#list_events) - Get event ids that were selected by the given campaign + +### [Beta.Observability.ChatCompletionEvents](https://github.com/mistralai/client-python/blob/main/docs/sdks/chatcompletionevents/README.md) + +* [search](https://github.com/mistralai/client-python/blob/main/docs/sdks/chatcompletionevents/README.md#search) - Get Chat Completion Events +* [search_ids](https://github.com/mistralai/client-python/blob/main/docs/sdks/chatcompletionevents/README.md#search_ids) - Alternative to /search that returns only the IDs and that can return many IDs at once +* [fetch](https://github.com/mistralai/client-python/blob/main/docs/sdks/chatcompletionevents/README.md#fetch) - Get Chat Completion Event +* [fetch_similar_events](https://github.com/mistralai/client-python/blob/main/docs/sdks/chatcompletionevents/README.md#fetch_similar_events) - Get Similar Chat Completion Events +* [judge](https://github.com/mistralai/client-python/blob/main/docs/sdks/chatcompletionevents/README.md#judge) - Run Judge on an event based on the given options + +#### [Beta.Observability.ChatCompletionEvents.Fields](https://github.com/mistralai/client-python/blob/main/docs/sdks/fields/README.md) + +* [list](https://github.com/mistralai/client-python/blob/main/docs/sdks/fields/README.md#list) - Get Chat Completion Fields +* [fetch_options](https://github.com/mistralai/client-python/blob/main/docs/sdks/fields/README.md#fetch_options) - Get Chat Completion Field Options +* [fetch_option_counts](https://github.com/mistralai/client-python/blob/main/docs/sdks/fields/README.md#fetch_option_counts) - Get Chat Completion Field Options Counts + +### [Beta.Observability.Datasets](https://github.com/mistralai/client-python/blob/main/docs/sdks/datasets/README.md) + +* [create](https://github.com/mistralai/client-python/blob/main/docs/sdks/datasets/README.md#create) - Create a new empty dataset +* [list](https://github.com/mistralai/client-python/blob/main/docs/sdks/datasets/README.md#list) - List existing datasets +* [fetch](https://github.com/mistralai/client-python/blob/main/docs/sdks/datasets/README.md#fetch) - Get dataset by id +* [delete](https://github.com/mistralai/client-python/blob/main/docs/sdks/datasets/README.md#delete) - Delete a dataset +* [update](https://github.com/mistralai/client-python/blob/main/docs/sdks/datasets/README.md#update) - Patch dataset +* [list_records](https://github.com/mistralai/client-python/blob/main/docs/sdks/datasets/README.md#list_records) - List existing records in the dataset +* [create_record](https://github.com/mistralai/client-python/blob/main/docs/sdks/datasets/README.md#create_record) - Add a conversation to the dataset +* [import_from_campaign](https://github.com/mistralai/client-python/blob/main/docs/sdks/datasets/README.md#import_from_campaign) - Populate the dataset with a campaign +* [import_from_explorer](https://github.com/mistralai/client-python/blob/main/docs/sdks/datasets/README.md#import_from_explorer) - Populate the dataset with samples from the explorer +* [import_from_file](https://github.com/mistralai/client-python/blob/main/docs/sdks/datasets/README.md#import_from_file) - Populate the dataset with samples from an uploaded file +* [import_from_playground](https://github.com/mistralai/client-python/blob/main/docs/sdks/datasets/README.md#import_from_playground) - Populate the dataset with samples from the playground +* [import_from_dataset_records](https://github.com/mistralai/client-python/blob/main/docs/sdks/datasets/README.md#import_from_dataset_records) - Populate the dataset with samples from another dataset +* [export_to_jsonl](https://github.com/mistralai/client-python/blob/main/docs/sdks/datasets/README.md#export_to_jsonl) - Export to the Files API and retrieve presigned URL to download the resulting JSONL file +* [fetch_task](https://github.com/mistralai/client-python/blob/main/docs/sdks/datasets/README.md#fetch_task) - Get status of a dataset import task +* [list_tasks](https://github.com/mistralai/client-python/blob/main/docs/sdks/datasets/README.md#list_tasks) - List import tasks for the given dataset + +#### [Beta.Observability.Datasets.Records](https://github.com/mistralai/client-python/blob/main/docs/sdks/records/README.md) + +* [fetch](https://github.com/mistralai/client-python/blob/main/docs/sdks/records/README.md#fetch) - Get the content of a given conversation from a dataset +* [delete](https://github.com/mistralai/client-python/blob/main/docs/sdks/records/README.md#delete) - Delete a record from a dataset +* [bulk_delete](https://github.com/mistralai/client-python/blob/main/docs/sdks/records/README.md#bulk_delete) - Delete multiple records from datasets +* [judge](https://github.com/mistralai/client-python/blob/main/docs/sdks/records/README.md#judge) - Run Judge on a dataset record based on the given options +* [update_payload](https://github.com/mistralai/client-python/blob/main/docs/sdks/records/README.md#update_payload) - Update a dataset record conversation payload +* [update_properties](https://github.com/mistralai/client-python/blob/main/docs/sdks/records/README.md#update_properties) - Update conversation properties + +### [Beta.Observability.Judges](https://github.com/mistralai/client-python/blob/main/docs/sdks/judges/README.md) + +* [create](https://github.com/mistralai/client-python/blob/main/docs/sdks/judges/README.md#create) - Create a new judge +* [list](https://github.com/mistralai/client-python/blob/main/docs/sdks/judges/README.md#list) - Get judges with optional filtering and search +* [fetch](https://github.com/mistralai/client-python/blob/main/docs/sdks/judges/README.md#fetch) - Get judge by id +* [delete](https://github.com/mistralai/client-python/blob/main/docs/sdks/judges/README.md#delete) - Delete a judge +* [update](https://github.com/mistralai/client-python/blob/main/docs/sdks/judges/README.md#update) - Update a judge + +### [Chat](https://github.com/mistralai/client-python/blob/main/docs/sdks/chat/README.md) + +* [complete](https://github.com/mistralai/client-python/blob/main/docs/sdks/chat/README.md#complete) - Chat Completion +* [stream](https://github.com/mistralai/client-python/blob/main/docs/sdks/chat/README.md#stream) - Stream chat completion + +### [Classifiers](https://github.com/mistralai/client-python/blob/main/docs/sdks/classifiers/README.md) + +* [moderate](https://github.com/mistralai/client-python/blob/main/docs/sdks/classifiers/README.md#moderate) - Moderations +* [moderate_chat](https://github.com/mistralai/client-python/blob/main/docs/sdks/classifiers/README.md#moderate_chat) - Chat Moderations +* [classify](https://github.com/mistralai/client-python/blob/main/docs/sdks/classifiers/README.md#classify) - Classifications +* [classify_chat](https://github.com/mistralai/client-python/blob/main/docs/sdks/classifiers/README.md#classify_chat) - Chat Classifications + +### [Embeddings](https://github.com/mistralai/client-python/blob/main/docs/sdks/embeddings/README.md) + +* [create](https://github.com/mistralai/client-python/blob/main/docs/sdks/embeddings/README.md#create) - Embeddings + +### [Files](https://github.com/mistralai/client-python/blob/main/docs/sdks/files/README.md) + +* [upload](https://github.com/mistralai/client-python/blob/main/docs/sdks/files/README.md#upload) - Upload File +* [list](https://github.com/mistralai/client-python/blob/main/docs/sdks/files/README.md#list) - List Files +* [retrieve](https://github.com/mistralai/client-python/blob/main/docs/sdks/files/README.md#retrieve) - Retrieve File +* [delete](https://github.com/mistralai/client-python/blob/main/docs/sdks/files/README.md#delete) - Delete File +* [download](https://github.com/mistralai/client-python/blob/main/docs/sdks/files/README.md#download) - Download File +* [get_signed_url](https://github.com/mistralai/client-python/blob/main/docs/sdks/files/README.md#get_signed_url) - Get Signed Url + +### [Fim](https://github.com/mistralai/client-python/blob/main/docs/sdks/fim/README.md) + +* [complete](https://github.com/mistralai/client-python/blob/main/docs/sdks/fim/README.md#complete) - Fim Completion +* [stream](https://github.com/mistralai/client-python/blob/main/docs/sdks/fim/README.md#stream) - Stream fim completion + +### [FineTuning.Jobs](https://github.com/mistralai/client-python/blob/main/docs/sdks/finetuningjobs/README.md) + +* [list](https://github.com/mistralai/client-python/blob/main/docs/sdks/finetuningjobs/README.md#list) - Get Fine Tuning Jobs +* [create](https://github.com/mistralai/client-python/blob/main/docs/sdks/finetuningjobs/README.md#create) - Create Fine Tuning Job +* [get](https://github.com/mistralai/client-python/blob/main/docs/sdks/finetuningjobs/README.md#get) - Get Fine Tuning Job +* [cancel](https://github.com/mistralai/client-python/blob/main/docs/sdks/finetuningjobs/README.md#cancel) - Cancel Fine Tuning Job +* [start](https://github.com/mistralai/client-python/blob/main/docs/sdks/finetuningjobs/README.md#start) - Start Fine Tuning Job + +### [Models](https://github.com/mistralai/client-python/blob/main/docs/sdks/models/README.md) + +* [list](https://github.com/mistralai/client-python/blob/main/docs/sdks/models/README.md#list) - List Models +* [retrieve](https://github.com/mistralai/client-python/blob/main/docs/sdks/models/README.md#retrieve) - Retrieve Model +* [delete](https://github.com/mistralai/client-python/blob/main/docs/sdks/models/README.md#delete) - Delete Model +* [update](https://github.com/mistralai/client-python/blob/main/docs/sdks/models/README.md#update) - Update Fine Tuned Model +* [archive](https://github.com/mistralai/client-python/blob/main/docs/sdks/models/README.md#archive) - Archive Fine Tuned Model +* [unarchive](https://github.com/mistralai/client-python/blob/main/docs/sdks/models/README.md#unarchive) - Unarchive Fine Tuned Model + +### [Ocr](https://github.com/mistralai/client-python/blob/main/docs/sdks/ocr/README.md) + +* [process](https://github.com/mistralai/client-python/blob/main/docs/sdks/ocr/README.md#process) - OCR + +
+ + + +## Server-sent event streaming + +[Server-sent events][mdn-sse] are used to stream content from certain +operations. These operations will expose the stream as [Generator][generator] that +can be consumed using a simple `for` loop. The loop will +terminate when the server no longer has any events to send and closes the +underlying connection. + +The stream is also a [Context Manager][context-manager] and can be used with the `with` statement and will close the +underlying connection when the context is exited. + +```python +from mistralai.client import Mistral +import os + + +with Mistral( + api_key=os.getenv("MISTRAL_API_KEY", ""), +) as mistral: + + res = mistral.beta.conversations.start_stream(inputs=[ + { + "object": "entry", + "type": "function.result", + "tool_call_id": "", + "result": "", + }, + ], stream=True, completion_args={ + "response_format": { + "type": "text", + }, + }) + + with res as event_stream: + for event in event_stream: + # handle event + print(event, flush=True) + +``` + +[mdn-sse]: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events +[generator]: https://book.pythontips.com/en/latest/generators.html +[context-manager]: https://book.pythontips.com/en/latest/context_managers.html + + + +## File uploads + +Certain SDK methods accept file objects as part of a request body or multi-part request. It is possible and typically recommended to upload files as a stream rather than reading the entire contents into memory. This avoids excessive memory consumption and potentially crashing with out-of-memory errors when working with very large files. The following example demonstrates how to attach a file stream to a request. + +> [!TIP] +> +> For endpoints that handle file uploads bytes arrays can also be used. However, using streams is recommended for large files. +> + +```python +from mistralai.client import Mistral +import os + + +with Mistral( + api_key=os.getenv("MISTRAL_API_KEY", ""), +) as mistral: + + res = mistral.beta.libraries.documents.upload(library_id="a02150d9-5ee0-4877-b62c-28b1fcdf3b76", file={ + "file_name": "example.file", + "content": open("example.file", "rb"), + }) + + # Handle response + print(res) + +``` + + + +## Retries + +Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK. + +To change the default retry strategy for a single API call, simply provide a `RetryConfig` object to the call: +```python +from mistralai.client import Mistral +from mistralai.client.utils import BackoffStrategy, RetryConfig +import os + + +with Mistral( + api_key=os.getenv("MISTRAL_API_KEY", ""), +) as mistral: + + res = mistral.models.list( + retries=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False)) + + # Handle response + print(res) + +``` + +If you'd like to override the default retry strategy for all operations that support retries, you can use the `retry_config` optional parameter when initializing the SDK: +```python +from mistralai.client import Mistral +from mistralai.client.utils import BackoffStrategy, RetryConfig +import os + + +with Mistral( + retry_config=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False), + api_key=os.getenv("MISTRAL_API_KEY", ""), +) as mistral: + + res = mistral.models.list() + + # Handle response + print(res) + +``` + + + +## Error Handling + +[`MistralError`](https://github.com/mistralai/client-python/blob/main/src/mistralai/client/errors/mistralerror.py) is the base class for all HTTP error responses. It has the following properties: + +| Property | Type | Description | +| ------------------ | ---------------- | --------------------------------------------------------------------------------------- | +| `err.message` | `str` | Error message | +| `err.status_code` | `int` | HTTP response status code eg `404` | +| `err.headers` | `httpx.Headers` | HTTP response headers | +| `err.body` | `str` | HTTP body. Can be empty string if no body is returned. | +| `err.raw_response` | `httpx.Response` | Raw HTTP response | +| `err.data` | | Optional. Some errors may contain structured data. [See Error Classes](#error-classes). | + +### Example +```python +from mistralai.client import Mistral, errors +import os + + +with Mistral( + api_key=os.getenv("MISTRAL_API_KEY", ""), +) as mistral: + res = None + try: + + res = mistral.models.list() + + # Handle response + print(res) + + + except errors.MistralError as e: + # The base class for HTTP error responses + print(e.message) + print(e.status_code) + print(e.body) + print(e.headers) + print(e.raw_response) + + # Depending on the method different errors may be thrown + if isinstance(e, errors.HTTPValidationError): + print(e.data.detail) # Optional[List[models.ValidationError]] +``` + +### Error Classes +**Primary error:** +* [`MistralError`](https://github.com/mistralai/client-python/blob/main/src/mistralai/client/errors/mistralerror.py): The base class for HTTP error responses. + +
Less common errors (7) + +
+ +**Network errors:** +* [`httpx.RequestError`](https://www.python-httpx.org/exceptions/#httpx.RequestError): Base class for request errors. + * [`httpx.ConnectError`](https://www.python-httpx.org/exceptions/#httpx.ConnectError): HTTP client was unable to make a request to a server. + * [`httpx.TimeoutException`](https://www.python-httpx.org/exceptions/#httpx.TimeoutException): HTTP request timed out. + + +**Inherit from [`MistralError`](https://github.com/mistralai/client-python/blob/main/src/mistralai/client/errors/mistralerror.py)**: +* [`HTTPValidationError`](https://github.com/mistralai/client-python/blob/main/src/mistralai/client/errors/httpvalidationerror.py): Validation Error. Status code `422`. Applicable to 60 of 121 methods.* +* [`ObservabilityError`](https://github.com/mistralai/client-python/blob/main/src/mistralai/client/errors/observabilityerror.py): Bad Request - Invalid request parameters or data. Applicable to 40 of 121 methods.* +* [`ResponseValidationError`](https://github.com/mistralai/client-python/blob/main/src/mistralai/client/errors/responsevalidationerror.py): Type mismatch between the response data and the expected Pydantic model. Provides access to the Pydantic validation error via the `cause` attribute. + +
+ +\* Check [the method documentation](#available-resources-and-operations) to see if the error is applicable. + + + +## Server Selection + +### Select Server by Name + +You can override the default server globally by passing a server name to the `server: str` optional parameter when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the names associated with the available servers: + +| Name | Server | Description | +| ---- | ------------------------ | -------------------- | +| `eu` | `https://api.mistral.ai` | EU Production server | + +#### Example + +```python +from mistralai.client import Mistral +import os + + +with Mistral( + server="eu", + api_key=os.getenv("MISTRAL_API_KEY", ""), +) as mistral: + + res = mistral.models.list() + + # Handle response + print(res) + +``` + +### Override Server URL Per-Client + +The default server can also be overridden globally by passing a URL to the `server_url: str` optional parameter when initializing the SDK client instance. For example: +```python +from mistralai.client import Mistral +import os + + +with Mistral( + server_url="https://api.mistral.ai", + api_key=os.getenv("MISTRAL_API_KEY", ""), +) as mistral: + + res = mistral.models.list() + + # Handle response + print(res) + +``` + + + +## Custom HTTP Client + +The Python SDK makes API calls using the [httpx](https://www.python-httpx.org/) HTTP library. In order to provide a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration, you can initialize the SDK client with your own HTTP client instance. +Depending on whether you are using the sync or async version of the SDK, you can pass an instance of `HttpClient` or `AsyncHttpClient` respectively, which are Protocols ensuring that the client has the necessary methods to make API calls. +This allows you to wrap the client with your own custom logic, such as adding custom headers, logging, or error handling, or you can just pass an instance of `httpx.Client` or `httpx.AsyncClient` directly. + +For example, you could specify a header for every request that this SDK makes as follows: +```python +from mistralai.client import Mistral +import httpx + +http_client = httpx.Client(headers={"x-custom-header": "someValue"}) +s = Mistral(client=http_client) +``` + +or you could wrap the client with your own custom logic: +```python +from mistralai.client import Mistral +from mistralai.client.httpclient import AsyncHttpClient +import httpx + +class CustomClient(AsyncHttpClient): + client: AsyncHttpClient + + def __init__(self, client: AsyncHttpClient): + self.client = client + + async def send( + self, + request: httpx.Request, + *, + stream: bool = False, + auth: Union[ + httpx._types.AuthTypes, httpx._client.UseClientDefault, None + ] = httpx.USE_CLIENT_DEFAULT, + follow_redirects: Union[ + bool, httpx._client.UseClientDefault + ] = httpx.USE_CLIENT_DEFAULT, + ) -> httpx.Response: + request.headers["Client-Level-Header"] = "added by client" + + return await self.client.send( + request, stream=stream, auth=auth, follow_redirects=follow_redirects + ) + + def build_request( + self, + method: str, + url: httpx._types.URLTypes, + *, + content: Optional[httpx._types.RequestContent] = None, + data: Optional[httpx._types.RequestData] = None, + files: Optional[httpx._types.RequestFiles] = None, + json: Optional[Any] = None, + params: Optional[httpx._types.QueryParamTypes] = None, + headers: Optional[httpx._types.HeaderTypes] = None, + cookies: Optional[httpx._types.CookieTypes] = None, + timeout: Union[ + httpx._types.TimeoutTypes, httpx._client.UseClientDefault + ] = httpx.USE_CLIENT_DEFAULT, + extensions: Optional[httpx._types.RequestExtensions] = None, + ) -> httpx.Request: + return self.client.build_request( + method, + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + timeout=timeout, + extensions=extensions, + ) + +s = Mistral(async_client=CustomClient(httpx.AsyncClient())) +``` + + + +## Authentication + +### Per-Client Security Schemes + +This SDK supports the following security scheme globally: + +| Name | Type | Scheme | Environment Variable | +| --------- | ---- | ----------- | -------------------- | +| `api_key` | http | HTTP Bearer | `MISTRAL_API_KEY` | + +To authenticate with the API the `api_key` parameter must be set when initializing the SDK client instance. For example: +```python +from mistralai.client import Mistral +import os + + +with Mistral( + api_key=os.getenv("MISTRAL_API_KEY", ""), +) as mistral: + + res = mistral.models.list() + + # Handle response + print(res) + +``` + + + +## Resource Management + +The `Mistral` class implements the context manager protocol and registers a finalizer function to close the underlying sync and async HTTPX clients it uses under the hood. This will close HTTP connections, release memory and free up other resources held by the SDK. In short-lived Python programs and notebooks that make a few SDK method calls, resource management may not be a concern. However, in longer-lived programs, it is beneficial to create a single SDK instance via a [context manager][context-manager] and reuse it across the application. + +[context-manager]: https://docs.python.org/3/reference/datamodel.html#context-managers + +```python +from mistralai.client import Mistral +import os +def main(): + + with Mistral( + api_key=os.getenv("MISTRAL_API_KEY", ""), + ) as mistral: + pass # Rest of application here... + + +# Or when using async: +async def amain(): + + async with Mistral( + api_key=os.getenv("MISTRAL_API_KEY", ""), + ) as mistral: + pass # Rest of application here... +``` + + + +## Debugging + +You can setup your SDK to emit debug logs for SDK requests and responses. + +You can pass your own logger class directly into your SDK. +```python +from mistralai.client import Mistral +import logging + +logging.basicConfig(level=logging.DEBUG) +s = Mistral(debug_logger=logging.getLogger("mistralai.client")) +``` + +You can also enable a default debug logger by setting an environment variable `MISTRAL_DEBUG` to true. + + + +## IDE Support + +### PyCharm + +Generally, the SDK will work well with most IDEs out of the box. However, when using PyCharm, you can enjoy much better integration with Pydantic by installing an additional plugin. + +- [PyCharm Pydantic Plugin](https://docs.pydantic.dev/latest/integrations/pycharm/) + + + + +# Development + +## Contributions + +While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. +We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release. diff --git a/README.md b/README.md index 971372f9..7ce8434b 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,8 @@ # Mistral Python Client -> [!NOTE] -> **Looking for v1 documentation?** This is the documentation for the **latest** version (v2) of the `mistralai` SDK, available on PyPI. -> -> **[Go to the v1 branch for v1 documentation](https://github.com/mistralai/client-python/tree/v1)** - ## Migrating from v1 -If you are upgrading from v1 to v2, check the [migration guide](MIGRATION.md) for details on breaking changes and how to update your code. +If you are upgrading from v1 to v2, check the [migration guide](https://github.com/mistralai/client-python/blob/main/MIGRATION.md) for details on breaking changes and how to update your code. ## API Key Setup @@ -170,7 +165,7 @@ with Mistral( print(res) ``` -
+
The same SDK client can also be used to make asynchronous requests by importing asyncio. @@ -224,7 +219,7 @@ with Mistral( print(res) ``` -
+
The same SDK client can also be used to make asynchronous requests by importing asyncio. @@ -278,7 +273,7 @@ with Mistral( print(res) ``` -
+
The same SDK client can also be used to make asynchronous requests by importing asyncio. @@ -311,7 +306,7 @@ asyncio.run(main()) ### Create Embedding Request -This example shows how to create embedding request. +This example shows how to create an embedding request. ```python # Synchronous Example @@ -332,7 +327,7 @@ with Mistral( print(res) ``` -
+
The same SDK client can also be used to make asynchronous requests by importing asyncio. @@ -486,7 +481,7 @@ print(res.choices[0].message.content) ### [Beta.Agents](docs/sdks/betaagents/README.md) -* [create](docs/sdks/betaagents/README.md#create) - Create a agent that can be used within a conversation. +* [create](docs/sdks/betaagents/README.md#create) - Create an agent that can be used within a conversation. * [list](docs/sdks/betaagents/README.md#list) - List agent entities. * [get](docs/sdks/betaagents/README.md#get) - Retrieve an agent entity. * [update](docs/sdks/betaagents/README.md#update) - Update an agent entity. @@ -526,7 +521,7 @@ print(res.choices[0].message.content) * [list](docs/sdks/libraries/README.md#list) - List all libraries you have access to. * [create](docs/sdks/libraries/README.md#create) - Create a new Library. * [get](docs/sdks/libraries/README.md#get) - Detailed information about a specific Library. -* [delete](docs/sdks/libraries/README.md#delete) - Delete a library and all of it's document. +* [delete](docs/sdks/libraries/README.md#delete) - Delete a library and all of its documents. * [update](docs/sdks/libraries/README.md#update) - Update a library. #### [Beta.Libraries.Accesses](docs/sdks/accesses/README.md) @@ -752,8 +747,8 @@ with Mistral( api_key=os.getenv("MISTRAL_API_KEY", ""), ) as mistral: - res = mistral.models.list(, - RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False)) + res = mistral.models.list( + retries=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False)) # Handle response print(res) @@ -904,10 +899,10 @@ with Mistral( ## Custom HTTP Client The Python SDK makes API calls using the [httpx](https://www.python-httpx.org/) HTTP library. In order to provide a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration, you can initialize the SDK client with your own HTTP client instance. -Depending on whether you are using the sync or async version of the SDK, you can pass an instance of `HttpClient` or `AsyncHttpClient` respectively, which are Protocol's ensuring that the client has the necessary methods to make API calls. +Depending on whether you are using the sync or async version of the SDK, you can pass an instance of `HttpClient` or `AsyncHttpClient` respectively, which are Protocols ensuring that the client has the necessary methods to make API calls. This allows you to wrap the client with your own custom logic, such as adding custom headers, logging, or error handling, or you can just pass an instance of `httpx.Client` or `httpx.AsyncClient` directly. -For example, you could specify a header for every request that this sdk makes as follows: +For example, you could specify a header for every request that this SDK makes as follows: ```python from mistralai.client import Mistral import httpx @@ -1025,7 +1020,7 @@ def main(): with Mistral( api_key=os.getenv("MISTRAL_API_KEY", ""), ) as mistral: - # Rest of application here... + pass # Rest of application here... # Or when using async: @@ -1034,7 +1029,7 @@ async def amain(): async with Mistral( api_key=os.getenv("MISTRAL_API_KEY", ""), ) as mistral: - # Rest of application here... + pass # Rest of application here... ``` diff --git a/USAGE.md b/USAGE.md index 9d32240a..bb01b160 100644 --- a/USAGE.md +++ b/USAGE.md @@ -26,7 +26,7 @@ with Mistral( print(res) ``` -
+
The same SDK client can also be used to make asynchronous requests by importing asyncio. @@ -80,7 +80,7 @@ with Mistral( print(res) ``` -
+
The same SDK client can also be used to make asynchronous requests by importing asyncio. @@ -134,7 +134,7 @@ with Mistral( print(res) ``` -
+
The same SDK client can also be used to make asynchronous requests by importing asyncio. @@ -167,7 +167,7 @@ asyncio.run(main()) ### Create Embedding Request -This example shows how to create embedding request. +This example shows how to create an embedding request. ```python # Synchronous Example @@ -188,7 +188,7 @@ with Mistral( print(res) ``` -
+
The same SDK client can also be used to make asynchronous requests by importing asyncio. diff --git a/docs/models/chatcompletionrequest.md b/docs/models/chatcompletionrequest.md index 921161fa..2752d73e 100644 --- a/docs/models/chatcompletionrequest.md +++ b/docs/models/chatcompletionrequest.md @@ -5,7 +5,7 @@ | Field | Type | Required | Description | Example | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `model` | *str* | :heavy_check_mark: | ID of the model to use. You can use the [List Available Models](/api/#tag/models/operation/list_models_v1_models_get) API to see all of your available models, or see our [Model overview](/models) for model descriptions. | mistral-large-latest | +| `model` | *str* | :heavy_check_mark: | ID of the model to use. You can use the [List Available Models](https://docs.mistral.ai/api/#tag/models/operation/list_models_v1_models_get) API to see all of your available models, or see our [Model overview](https://docs.mistral.ai/models) for model descriptions. | mistral-large-latest | | `temperature` | *OptionalNullable[float]* | :heavy_minus_sign: | What sampling temperature to use, we recommend between 0.0 and 0.7. Higher values like 0.7 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. We generally recommend altering this or `top_p` but not both. The default value varies depending on the model you are targeting. Call the `/models` endpoint to retrieve the appropriate value. | | | `top_p` | *Optional[float]* | :heavy_minus_sign: | Nucleus sampling, where the model considers the results of the tokens with `top_p` probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or `temperature` but not both. | | | `max_tokens` | *OptionalNullable[int]* | :heavy_minus_sign: | The maximum number of tokens to generate in the completion. The token count of your prompt plus `max_tokens` cannot exceed the model's context length. | | diff --git a/docs/models/chatcompletionstreamrequest.md b/docs/models/chatcompletionstreamrequest.md index 8761f000..e7d542a6 100644 --- a/docs/models/chatcompletionstreamrequest.md +++ b/docs/models/chatcompletionstreamrequest.md @@ -5,7 +5,7 @@ | Field | Type | Required | Description | Example | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `model` | *str* | :heavy_check_mark: | ID of the model to use. You can use the [List Available Models](/api/#tag/models/operation/list_models_v1_models_get) API to see all of your available models, or see our [Model overview](/models) for model descriptions. | mistral-large-latest | +| `model` | *str* | :heavy_check_mark: | ID of the model to use. You can use the [List Available Models](https://docs.mistral.ai/api/#tag/models/operation/list_models_v1_models_get) API to see all of your available models, or see our [Model overview](https://docs.mistral.ai/models) for model descriptions. | mistral-large-latest | | `temperature` | *OptionalNullable[float]* | :heavy_minus_sign: | What sampling temperature to use, we recommend between 0.0 and 0.7. Higher values like 0.7 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. We generally recommend altering this or `top_p` but not both. The default value varies depending on the model you are targeting. Call the `/models` endpoint to retrieve the appropriate value. | | | `top_p` | *Optional[float]* | :heavy_minus_sign: | Nucleus sampling, where the model considers the results of the tokens with `top_p` probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or `temperature` but not both. | | | `max_tokens` | *OptionalNullable[int]* | :heavy_minus_sign: | The maximum number of tokens to generate in the completion. The token count of your prompt plus `max_tokens` cannot exceed the model's context length. | | diff --git a/docs/sdks/accesses/README.md b/docs/sdks/accesses/README.md index 51051e2f..09515e0b 100644 --- a/docs/sdks/accesses/README.md +++ b/docs/sdks/accesses/README.md @@ -98,7 +98,7 @@ with Mistral( ## delete -Given a library id, you can delete the access level of an entity. An owner cannot delete it's own access. You have to be the owner of the library to delete an acces other than yours. +Given a library id, you can delete the access level of an entity. An owner cannot delete its own access. You have to be the owner of the library to delete an access other than yours. ### Example Usage diff --git a/docs/sdks/agents/README.md b/docs/sdks/agents/README.md index 8a608370..d39e72ee 100644 --- a/docs/sdks/agents/README.md +++ b/docs/sdks/agents/README.md @@ -128,7 +128,7 @@ with Mistral( ### Response -**[Union[eventstreaming.EventStream[models.CompletionEvent], eventstreaming.EventStreamAsync[models.CompletionEvent]]](../../models/.md)** +**Union[eventstreaming.EventStream[models.CompletionEvent], eventstreaming.EventStreamAsync[models.CompletionEvent]]** ### Errors diff --git a/docs/sdks/betaagents/README.md b/docs/sdks/betaagents/README.md index b936538c..56773f08 100644 --- a/docs/sdks/betaagents/README.md +++ b/docs/sdks/betaagents/README.md @@ -6,7 +6,7 @@ ### Available Operations -* [create](#create) - Create a agent that can be used within a conversation. +* [create](#create) - Create an agent that can be used within a conversation. * [list](#list) - List agent entities. * [get](#get) - Retrieve an agent entity. * [update](#update) - Update an agent entity. @@ -111,7 +111,7 @@ with Mistral( ### Response -**[List[models.Agent]](../../models/.md)** +**List[models.Agent]** ### Errors @@ -330,7 +330,7 @@ with Mistral( ### Response -**[List[models.Agent]](../../models/.md)** +**List[models.Agent]** ### Errors @@ -456,7 +456,7 @@ with Mistral( ### Response -**[List[models.AgentAliasResponse]](../../models/.md)** +**List[models.AgentAliasResponse]** ### Errors diff --git a/docs/sdks/chat/README.md b/docs/sdks/chat/README.md index 1bf4aead..d43e42f2 100644 --- a/docs/sdks/chat/README.md +++ b/docs/sdks/chat/README.md @@ -43,7 +43,7 @@ with Mistral( | Parameter | Type | Required | Description | Example | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `model` | *str* | :heavy_check_mark: | ID of the model to use. You can use the [List Available Models](/api/#tag/models/operation/list_models_v1_models_get) API to see all of your available models, or see our [Model overview](/models) for model descriptions. | mistral-large-latest | +| `model` | *str* | :heavy_check_mark: | ID of the model to use. You can use the [List Available Models](https://docs.mistral.ai/api/#tag/models/operation/list_models_v1_models_get) API to see all of your available models, or see our [Model overview](https://docs.mistral.ai/models) for model descriptions. | mistral-large-latest | | `messages` | List[[models.ChatCompletionRequestMessage](../../models/chatcompletionrequestmessage.md)] | :heavy_check_mark: | The prompt(s) to generate completions for, encoded as a list of dict with role and content. | [
{
"role": "user",
"content": "Who is the best French painter? Answer in one short sentence."
}
] | | `temperature` | *OptionalNullable[float]* | :heavy_minus_sign: | What sampling temperature to use, we recommend between 0.0 and 0.7. Higher values like 0.7 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. We generally recommend altering this or `top_p` but not both. The default value varies depending on the model you are targeting. Call the `/models` endpoint to retrieve the appropriate value. | | | `top_p` | *Optional[float]* | :heavy_minus_sign: | Nucleus sampling, where the model considers the results of the tokens with `top_p` probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or `temperature` but not both. | | @@ -111,7 +111,7 @@ with Mistral( | Parameter | Type | Required | Description | Example | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `model` | *str* | :heavy_check_mark: | ID of the model to use. You can use the [List Available Models](/api/#tag/models/operation/list_models_v1_models_get) API to see all of your available models, or see our [Model overview](/models) for model descriptions. | mistral-large-latest | +| `model` | *str* | :heavy_check_mark: | ID of the model to use. You can use the [List Available Models](https://docs.mistral.ai/api/#tag/models/operation/list_models_v1_models_get) API to see all of your available models, or see our [Model overview](https://docs.mistral.ai/models) for model descriptions. | mistral-large-latest | | `messages` | List[[models.ChatCompletionStreamRequestMessage](../../models/chatcompletionstreamrequestmessage.md)] | :heavy_check_mark: | The prompt(s) to generate completions for, encoded as a list of dict with role and content. | [
{
"role": "user",
"content": "Who is the best French painter? Answer in one short sentence."
}
] | | `temperature` | *OptionalNullable[float]* | :heavy_minus_sign: | What sampling temperature to use, we recommend between 0.0 and 0.7. Higher values like 0.7 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. We generally recommend altering this or `top_p` but not both. The default value varies depending on the model you are targeting. Call the `/models` endpoint to retrieve the appropriate value. | | | `top_p` | *Optional[float]* | :heavy_minus_sign: | Nucleus sampling, where the model considers the results of the tokens with `top_p` probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or `temperature` but not both. | | @@ -134,7 +134,7 @@ with Mistral( ### Response -**[Union[eventstreaming.EventStream[models.CompletionEvent], eventstreaming.EventStreamAsync[models.CompletionEvent]]](../../models/.md)** +**Union[eventstreaming.EventStream[models.CompletionEvent], eventstreaming.EventStreamAsync[models.CompletionEvent]]** ### Errors diff --git a/docs/sdks/conversations/README.md b/docs/sdks/conversations/README.md index 0803b398..12d94765 100644 --- a/docs/sdks/conversations/README.md +++ b/docs/sdks/conversations/README.md @@ -110,7 +110,7 @@ with Mistral( ### Response -**[List[models.AgentsAPIV1ConversationsListResponse]](../../models/.md)** +**List[models.AgentsAPIV1ConversationsListResponse]** ### Errors @@ -441,7 +441,7 @@ with Mistral( ### Response -**[Union[eventstreaming.EventStream[models.ConversationEvents], eventstreaming.EventStreamAsync[models.ConversationEvents]]](../../models/.md)** +**Union[eventstreaming.EventStream[models.ConversationEvents], eventstreaming.EventStreamAsync[models.ConversationEvents]]** ### Errors @@ -494,7 +494,7 @@ with Mistral( ### Response -**[Union[eventstreaming.EventStream[models.ConversationEvents], eventstreaming.EventStreamAsync[models.ConversationEvents]]](../../models/.md)** +**Union[eventstreaming.EventStream[models.ConversationEvents], eventstreaming.EventStreamAsync[models.ConversationEvents]]** ### Errors @@ -550,7 +550,7 @@ with Mistral( ### Response -**[Union[eventstreaming.EventStream[models.ConversationEvents], eventstreaming.EventStreamAsync[models.ConversationEvents]]](../../models/.md)** +**Union[eventstreaming.EventStream[models.ConversationEvents], eventstreaming.EventStreamAsync[models.ConversationEvents]]** ### Errors diff --git a/docs/sdks/documents/README.md b/docs/sdks/documents/README.md index 2c9440f9..48ddb6f8 100644 --- a/docs/sdks/documents/README.md +++ b/docs/sdks/documents/README.md @@ -349,7 +349,7 @@ with Mistral( ### Response -**[str](../../models/responselibrariesdocumentsgetsignedurlv1.md)** +**str** ### Errors @@ -391,7 +391,7 @@ with Mistral( ### Response -**[str](../../models/responselibrariesdocumentsgetextractedtextsignedurlv1.md)** +**str** ### Errors diff --git a/docs/sdks/files/README.md b/docs/sdks/files/README.md index 7db76611..bceebdf8 100644 --- a/docs/sdks/files/README.md +++ b/docs/sdks/files/README.md @@ -222,7 +222,7 @@ with Mistral( ### Response -**[httpx.Response](../../models/.md)** +**httpx.Response** ### Errors diff --git a/docs/sdks/fim/README.md b/docs/sdks/fim/README.md index 49151bf5..d06ed31e 100644 --- a/docs/sdks/fim/README.md +++ b/docs/sdks/fim/README.md @@ -104,7 +104,7 @@ with Mistral( ### Response -**[Union[eventstreaming.EventStream[models.CompletionEvent], eventstreaming.EventStreamAsync[models.CompletionEvent]]](../../models/.md)** +**Union[eventstreaming.EventStream[models.CompletionEvent], eventstreaming.EventStreamAsync[models.CompletionEvent]]** ### Errors diff --git a/docs/sdks/libraries/README.md b/docs/sdks/libraries/README.md index 7df1ef4e..6a514e1f 100644 --- a/docs/sdks/libraries/README.md +++ b/docs/sdks/libraries/README.md @@ -9,7 +9,7 @@ * [list](#list) - List all libraries you have access to. * [create](#create) - Create a new Library. * [get](#get) - Detailed information about a specific Library. -* [delete](#delete) - Delete a library and all of it's document. +* [delete](#delete) - Delete a library and all of its documents. * [update](#update) - Update a library. ## list diff --git a/docs/sdks/transcriptions/README.md b/docs/sdks/transcriptions/README.md index 97703c9b..7357f9e9 100644 --- a/docs/sdks/transcriptions/README.md +++ b/docs/sdks/transcriptions/README.md @@ -99,7 +99,7 @@ with Mistral( ### Response -**[Union[eventstreaming.EventStream[models.TranscriptionStreamEvents], eventstreaming.EventStreamAsync[models.TranscriptionStreamEvents]]](../../models/.md)** +**Union[eventstreaming.EventStream[models.TranscriptionStreamEvents], eventstreaming.EventStreamAsync[models.TranscriptionStreamEvents]]** ### Errors diff --git a/examples/mistral/agents/async_agents_no_streaming.py b/examples/mistral/agents/async_agents_no_streaming.py index 6041cad3..bb2d767a 100755 --- a/examples/mistral/agents/async_agents_no_streaming.py +++ b/examples/mistral/agents/async_agents_no_streaming.py @@ -6,19 +6,29 @@ from mistralai.client import Mistral from mistralai.client.models import UserMessage +MODEL = "mistral-medium-latest" + async def main(): api_key = os.environ["MISTRAL_API_KEY"] - agent_id = os.environ["MISTRAL_AGENT_ID"] - client = Mistral(api_key=api_key) - chat_response = await client.agents.complete_async( - agent_id=agent_id, - messages=[UserMessage(content="What is the best French cheese?")], + # Create a fresh agent for this run to avoid version accumulation + agent = client.beta.agents.create( + model=MODEL, + name="cheese-expert-example", + instructions="You are a helpful assistant.", ) - print(chat_response.choices[0].message.content) + try: + chat_response = await client.agents.complete_async( + agent_id=agent.id, + messages=[UserMessage(content="What is the best French cheese?")], + ) + + print(chat_response.choices[0].message.content) + finally: + client.beta.agents.delete(agent_id=agent.id) if __name__ == "__main__": diff --git a/examples/mistral/agents/async_multi_turn_conversation.py b/examples/mistral/agents/async_multi_turn_conversation.py index 26c2378f..9a41a097 100644 --- a/examples/mistral/agents/async_multi_turn_conversation.py +++ b/examples/mistral/agents/async_multi_turn_conversation.py @@ -1,10 +1,10 @@ import os -from mistralai.client import Mistral - -from mistralai.extra.run.context import RunContext +import asyncio import logging import time -import asyncio + +from mistralai.client import Mistral +from mistralai.extra.run.context import RunContext MODEL = "mistral-medium-latest" @@ -22,23 +22,30 @@ async def main(): api_key = os.environ["MISTRAL_API_KEY"] - mistral_agent_id = os.environ["MISTRAL_AGENT_ID"] client = Mistral( api_key=api_key, debug_logger=logging.getLogger("mistralai") ) - async with RunContext( - agent_id=mistral_agent_id - ) as run_context: - run_context.register_func(get_secret_santa_assignment) - run_context.register_func(get_gift_wishlist) - run_context.register_func(buy_gift) - run_context.register_func(send_gift) + # Create a fresh agent for this run to avoid version accumulation + agent = client.beta.agents.create( + model=MODEL, + name="secret-santa-example", + instructions="You are a helpful assistant that helps with Secret Santa.", + ) + + try: + async with RunContext(agent_id=agent.id) as run_context: + run_context.register_func(get_secret_santa_assignment) + run_context.register_func(get_gift_wishlist) + run_context.register_func(buy_gift) + run_context.register_func(send_gift) - await client.beta.conversations.run_async( - run_ctx=run_context, - inputs=USER_MESSAGE, - ) + await client.beta.conversations.run_async( + run_ctx=run_context, + inputs=USER_MESSAGE, + ) + finally: + client.beta.agents.delete(agent_id=agent.id) def get_secret_santa_assignment(): @@ -66,4 +73,4 @@ def send_gift(friend_name: str, gift_name: str, website: str): if __name__ == "__main__": - asyncio.run(main()) \ No newline at end of file + asyncio.run(main()) diff --git a/packages/azure/.genignore b/packages/azure/.genignore index 6bdf6621..c4f3ac71 100644 --- a/packages/azure/.genignore +++ b/packages/azure/.genignore @@ -4,3 +4,4 @@ src/mistralai/azure/client/_hooks/registration.py README.md USAGE.md docs/sdks/**/README.md +scripts/prepare_readme.py diff --git a/packages/azure/README.md b/packages/azure/README.md index 6eff040f..f1f865f6 100644 --- a/packages/azure/README.md +++ b/packages/azure/README.md @@ -58,7 +58,7 @@ if res is not None: print(res.choices[0].message.content) ``` -
+
The same SDK client can also be used to make asynchronous requests by importing asyncio. ```python @@ -326,10 +326,10 @@ if res is not None: ## Custom HTTP Client The Python SDK makes API calls using the [httpx](https://www.python-httpx.org/) HTTP library. In order to provide a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration, you can initialize the SDK client with your own HTTP client instance. -Depending on whether you are using the sync or async version of the SDK, you can pass an instance of `HttpClient` or `AsyncHttpClient` respectively, which are Protocol's ensuring that the client has the necessary methods to make API calls. +Depending on whether you are using the sync or async version of the SDK, you can pass an instance of `HttpClient` or `AsyncHttpClient` respectively, which are Protocols ensuring that the client has the necessary methods to make API calls. This allows you to wrap the client with your own custom logic, such as adding custom headers, logging, or error handling, or you can just pass an instance of `httpx.Client` or `httpx.AsyncClient` directly. -For example, you could specify a header for every request that this sdk makes as follows: +For example, you could specify a header for every request that this SDK makes as follows: ```python from mistralai.azure.client import MistralAzure import httpx diff --git a/packages/azure/USAGE.md b/packages/azure/USAGE.md index a4bc5147..f2641e8f 100644 --- a/packages/azure/USAGE.md +++ b/packages/azure/USAGE.md @@ -34,7 +34,7 @@ if res is not None: print(res.choices[0].message.content) ``` -
+
The same SDK client can also be used to make asynchronous requests by importing asyncio. ```python diff --git a/packages/azure/docs/sdks/chat/README.md b/packages/azure/docs/sdks/chat/README.md index 560ffa83..88735d97 100644 --- a/packages/azure/docs/sdks/chat/README.md +++ b/packages/azure/docs/sdks/chat/README.md @@ -50,7 +50,7 @@ if res is not None: | Parameter | Type | Required | Description | Example | | ----------------- | ----------------------------------------------------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | -| `messages` | List[[models.Messages](../../models/messages.md)] | :heavy_check_mark: | The prompt(s) to generate completions for, encoded as a list of dict with role and content. | {
"role": "user",
"content": "Who is the best French painter? Answer in one short sentence."
} | +| `messages` | List[models.Messages] | :heavy_check_mark: | The prompt(s) to generate completions for, encoded as a list of dict with role and content. | {
"role": "user",
"content": "Who is the best French painter? Answer in one short sentence."
} | | `model` | *OptionalNullable[str]* | :heavy_minus_sign: | The ID of the model to use for this request. | azureai | | `temperature` | *Optional[float]* | :heavy_minus_sign: | What sampling temperature to use, between 0.0 and 1.0. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. We generally recommend altering this or `top_p` but not both. | | | `top_p` | *Optional[float]* | :heavy_minus_sign: | Nucleus sampling, where the model considers the results of the tokens with `top_p` probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or `temperature` but not both. | | @@ -68,7 +68,7 @@ if res is not None: ### Response -**[Union[Generator[models.CompletionEvent, None, None], AsyncGenerator[models.CompletionEvent, None]]](../../models/.md)** +**Union[Generator[models.CompletionEvent, None, None], AsyncGenerator[models.CompletionEvent, None]]** ### Errors | Error Object | Status Code | Content Type | @@ -114,7 +114,7 @@ if res is not None: | Parameter | Type | Required | Description | Example | | ----------------- | --------------------------------------------------------------------------------------------------- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | -| `messages` | List[[models.ChatCompletionRequestMessages](../../models/chatcompletionrequestmessages.md)] | :heavy_check_mark: | The prompt(s) to generate completions for, encoded as a list of dict with role and content. | {
"role": "user",
"content": "Who is the best French painter? Answer in one short sentence."
} | +| `messages` | List[models.ChatCompletionRequestMessages] | :heavy_check_mark: | The prompt(s) to generate completions for, encoded as a list of dict with role and content. | {
"role": "user",
"content": "Who is the best French painter? Answer in one short sentence."
} | | `model` | *OptionalNullable[str]* | :heavy_minus_sign: | The ID of the model to use for this request. | azureai | | `temperature` | *Optional[float]* | :heavy_minus_sign: | What sampling temperature to use, between 0.0 and 1.0. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. We generally recommend altering this or `top_p` but not both. | | | `top_p` | *Optional[float]* | :heavy_minus_sign: | Nucleus sampling, where the model considers the results of the tokens with `top_p` probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or `temperature` but not both. | | diff --git a/packages/azure/pyproject.toml b/packages/azure/pyproject.toml index 8742bb24..334767bd 100644 --- a/packages/azure/pyproject.toml +++ b/packages/azure/pyproject.toml @@ -4,7 +4,7 @@ version = "2.0.0" description = "Python Client SDK for the Mistral AI API in Azure." authors = [{ name = "Mistral" }] requires-python = ">=3.10" -readme = "README.md" +readme = "README-PYPI.md" dependencies = [ "httpcore >=1.0.9", "httpx >=0.28.1", diff --git a/packages/azure/scripts/prepare_readme.py b/packages/azure/scripts/prepare_readme.py index 2b2577ea..a628b6b4 100644 --- a/packages/azure/scripts/prepare_readme.py +++ b/packages/azure/scripts/prepare_readme.py @@ -1,33 +1,45 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - import re import shutil +import sys + +GITHUB_URL = "https://github.com/mistralai/client-python.git" +BRANCH = "main" +REPO_SUBDIR = "packages/azure" +LINK_PATTERN = re.compile(r"(\[[^\]]+\]\()((?![a-zA-Z][a-zA-Z0-9+.-]*:|#)[^\)]+)(\))") + + +def _build_base_url(repo_url: str, branch: str, repo_subdir: str) -> str: + normalized = repo_url[:-4] if repo_url.endswith(".git") else repo_url + subdir = repo_subdir.strip("/") + if subdir: + subdir = f"{subdir}/" + return f"{normalized}/blob/{branch}/{subdir}" + + +def _normalize_relative_path(path: str) -> str: + if path.startswith("./"): + path = path[2:] + elif path.startswith("/"): + path = path[1:] + return path + + +def _rewrite_relative_links(contents: str, base_url: str) -> str: + return LINK_PATTERN.sub( + lambda m: f"{m.group(1)}{base_url}{_normalize_relative_path(m.group(2))}{m.group(3)}", + contents, + ) + try: - with open("README.md", "r", encoding="utf-8") as rh: - readme_contents = rh.read() - GITHUB_URL = "https://github.com/mistralai/client-python.git" - GITHUB_URL = ( - GITHUB_URL[: -len(".git")] if GITHUB_URL.endswith(".git") else GITHUB_URL - ) - REPO_SUBDIR = "packages/azure" - # Ensure the subdirectory has a trailing slash - if not REPO_SUBDIR.endswith("/"): - REPO_SUBDIR += "/" - # links on PyPI should have absolute URLs - readme_contents = re.sub( - r"(\[[^\]]+\]\()((?!https?:)[^\)]+)(\))", - lambda m: m.group(1) - + GITHUB_URL - + "/blob/master/" - + REPO_SUBDIR - + m.group(2) - + m.group(3), - readme_contents, - ) - - with open("README-PYPI.md", "w", encoding="utf-8") as wh: - wh.write(readme_contents) + with open("README.md", "r", encoding="utf-8") as fh: + readme_contents = fh.read() + + base_url = _build_base_url(GITHUB_URL, BRANCH, REPO_SUBDIR) + readme_contents = _rewrite_relative_links(readme_contents, base_url) + + with open("README-PYPI.md", "w", encoding="utf-8") as fh: + fh.write(readme_contents) except Exception as e: try: print("Failed to rewrite README.md to README-PYPI.md, copying original instead") @@ -36,3 +48,4 @@ except Exception as ie: print("Failed to copy README.md to README-PYPI.md") print(ie) + sys.exit(1) diff --git a/packages/gcp/.genignore b/packages/gcp/.genignore index 9a119b75..ac1791db 100644 --- a/packages/gcp/.genignore +++ b/packages/gcp/.genignore @@ -4,3 +4,4 @@ src/mistralai/gcp/client/_hooks/registration.py README.md USAGE.md docs/sdks/**/README.md +scripts/prepare_readme.py diff --git a/packages/gcp/README.md b/packages/gcp/README.md index 5b66766b..8a26cf2c 100644 --- a/packages/gcp/README.md +++ b/packages/gcp/README.md @@ -54,7 +54,7 @@ if res is not None: print(res.choices[0].message.content) ``` -
+
The same SDK client can also be used to make asynchronous requests by importing asyncio. ```python @@ -291,10 +291,10 @@ if res is not None: ## Custom HTTP Client The Python SDK makes API calls using the [httpx](https://www.python-httpx.org/) HTTP library. In order to provide a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration, you can initialize the SDK client with your own HTTP client instance. -Depending on whether you are using the sync or async version of the SDK, you can pass an instance of `HttpClient` or `AsyncHttpClient` respectively, which are Protocol's ensuring that the client has the necessary methods to make API calls. +Depending on whether you are using the sync or async version of the SDK, you can pass an instance of `HttpClient` or `AsyncHttpClient` respectively, which are Protocols ensuring that the client has the necessary methods to make API calls. This allows you to wrap the client with your own custom logic, such as adding custom headers, logging, or error handling, or you can just pass an instance of `httpx.Client` or `httpx.AsyncClient` directly. -For example, you could specify a header for every request that this sdk makes as follows: +For example, you could specify a header for every request that this SDK makes as follows: ```python import os from mistralai.gcp.client import MistralGCP diff --git a/packages/gcp/USAGE.md b/packages/gcp/USAGE.md index 3156349d..6ca6bdcd 100644 --- a/packages/gcp/USAGE.md +++ b/packages/gcp/USAGE.md @@ -31,7 +31,7 @@ if res is not None: print(res.choices[0].message.content) ``` -
+
The same SDK client can also be used to make asynchronous requests by importing asyncio. ```python diff --git a/packages/gcp/docs/models/chatcompletionrequest.md b/packages/gcp/docs/models/chatcompletionrequest.md index 8dbd4a82..78cce437 100644 --- a/packages/gcp/docs/models/chatcompletionrequest.md +++ b/packages/gcp/docs/models/chatcompletionrequest.md @@ -5,7 +5,7 @@ | Field | Type | Required | Description | Example | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `model` | *str* | :heavy_check_mark: | ID of the model to use. You can use the [List Available Models](/api/#tag/models/operation/list_models_v1_models_get) API to see all of your available models, or see our [Model overview](/models) for model descriptions. | mistral-large-latest | +| `model` | *str* | :heavy_check_mark: | ID of the model to use. You can use the [List Available Models](https://docs.mistral.ai/api/#tag/models/operation/list_models_v1_models_get) API to see all of your available models, or see our [Model overview](https://docs.mistral.ai/models) for model descriptions. | mistral-large-latest | | `temperature` | *OptionalNullable[float]* | :heavy_minus_sign: | What sampling temperature to use, we recommend between 0.0 and 0.7. Higher values like 0.7 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. We generally recommend altering this or `top_p` but not both. The default value varies depending on the model you are targeting. Call the `/models` endpoint to retrieve the appropriate value. | | | `top_p` | *Optional[float]* | :heavy_minus_sign: | Nucleus sampling, where the model considers the results of the tokens with `top_p` probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or `temperature` but not both. | | | `max_tokens` | *OptionalNullable[int]* | :heavy_minus_sign: | The maximum number of tokens to generate in the completion. The token count of your prompt plus `max_tokens` cannot exceed the model's context length. | | diff --git a/packages/gcp/docs/models/chatcompletionstreamrequest.md b/packages/gcp/docs/models/chatcompletionstreamrequest.md index db76b6c8..a26a85d7 100644 --- a/packages/gcp/docs/models/chatcompletionstreamrequest.md +++ b/packages/gcp/docs/models/chatcompletionstreamrequest.md @@ -5,7 +5,7 @@ | Field | Type | Required | Description | Example | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `model` | *str* | :heavy_check_mark: | ID of the model to use. You can use the [List Available Models](/api/#tag/models/operation/list_models_v1_models_get) API to see all of your available models, or see our [Model overview](/models) for model descriptions. | mistral-large-latest | +| `model` | *str* | :heavy_check_mark: | ID of the model to use. You can use the [List Available Models](https://docs.mistral.ai/api/#tag/models/operation/list_models_v1_models_get) API to see all of your available models, or see our [Model overview](https://docs.mistral.ai/models) for model descriptions. | mistral-large-latest | | `temperature` | *OptionalNullable[float]* | :heavy_minus_sign: | What sampling temperature to use, we recommend between 0.0 and 0.7. Higher values like 0.7 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. We generally recommend altering this or `top_p` but not both. The default value varies depending on the model you are targeting. Call the `/models` endpoint to retrieve the appropriate value. | | | `top_p` | *Optional[float]* | :heavy_minus_sign: | Nucleus sampling, where the model considers the results of the tokens with `top_p` probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or `temperature` but not both. | | | `max_tokens` | *OptionalNullable[int]* | :heavy_minus_sign: | The maximum number of tokens to generate in the completion. The token count of your prompt plus `max_tokens` cannot exceed the model's context length. | | diff --git a/packages/gcp/docs/sdks/chat/README.md b/packages/gcp/docs/sdks/chat/README.md index a1fdfd9a..ca80b3fd 100644 --- a/packages/gcp/docs/sdks/chat/README.md +++ b/packages/gcp/docs/sdks/chat/README.md @@ -44,8 +44,8 @@ if res is not None: | Parameter | Type | Required | Description | Example | | ----------------- | ----------------------------------------------------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | -| `messages` | List[[models.Messages](../../models/messages.md)] | :heavy_check_mark: | The prompt(s) to generate completions for, encoded as a list of dict with role and content. | {
"role": "user",
"content": "Who is the best French painter? Answer in one short sentence."
} | -| `model` | *OptionalNullable[str]* | :heavy_minus_sign: | ID of the model to use. You can use the [List Available Models](/api#operation/listModels) API to see all of your available models, or see our [Model overview](/models) for model descriptions. | mistral-small-latest | +| `messages` | List[models.Messages] | :heavy_check_mark: | The prompt(s) to generate completions for, encoded as a list of dict with role and content. | {
"role": "user",
"content": "Who is the best French painter? Answer in one short sentence."
} | +| `model` | *OptionalNullable[str]* | :heavy_minus_sign: | ID of the model to use. You can use the [List Available Models](https://docs.mistral.ai/api#operation/listModels) API to see all of your available models, or see our [Model overview](https://docs.mistral.ai/models) for model descriptions. | mistral-small-latest | | `temperature` | *Optional[float]* | :heavy_minus_sign: | What sampling temperature to use, between 0.0 and 1.0. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. We generally recommend altering this or `top_p` but not both. | | | `top_p` | *Optional[float]* | :heavy_minus_sign: | Nucleus sampling, where the model considers the results of the tokens with `top_p` probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or `temperature` but not both. | | | `max_tokens` | *OptionalNullable[int]* | :heavy_minus_sign: | The maximum number of tokens to generate in the completion. The token count of your prompt plus `max_tokens` cannot exceed the model's context length. | | @@ -61,7 +61,7 @@ if res is not None: ### Response -**[Union[Generator[models.CompletionEvent, None, None], AsyncGenerator[models.CompletionEvent, None]]](../../models/.md)** +**Union[Generator[models.CompletionEvent, None, None], AsyncGenerator[models.CompletionEvent, None]]** ### Errors | Error Object | Status Code | Content Type | @@ -101,8 +101,8 @@ if res is not None: | Parameter | Type | Required | Description | Example | | ----------------- | --------------------------------------------------------------------------------------------------- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | -| `messages` | List[[models.ChatCompletionRequestMessages](../../models/chatcompletionrequestmessages.md)] | :heavy_check_mark: | The prompt(s) to generate completions for, encoded as a list of dict with role and content. | {
"role": "user",
"content": "Who is the best French painter? Answer in one short sentence."
} | -| `model` | *OptionalNullable[str]* | :heavy_minus_sign: | ID of the model to use. You can use the [List Available Models](/api#operation/listModels) API to see all of your available models, or see our [Model overview](/models) for model descriptions. | mistral-small-latest | +| `messages` | List[models.ChatCompletionRequestMessages] | :heavy_check_mark: | The prompt(s) to generate completions for, encoded as a list of dict with role and content. | {
"role": "user",
"content": "Who is the best French painter? Answer in one short sentence."
} | +| `model` | *OptionalNullable[str]* | :heavy_minus_sign: | ID of the model to use. You can use the [List Available Models](https://docs.mistral.ai/api#operation/listModels) API to see all of your available models, or see our [Model overview](https://docs.mistral.ai/models) for model descriptions. | mistral-small-latest | | `temperature` | *Optional[float]* | :heavy_minus_sign: | What sampling temperature to use, between 0.0 and 1.0. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. We generally recommend altering this or `top_p` but not both. | | | `top_p` | *Optional[float]* | :heavy_minus_sign: | Nucleus sampling, where the model considers the results of the tokens with `top_p` probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or `temperature` but not both. | | | `max_tokens` | *OptionalNullable[int]* | :heavy_minus_sign: | The maximum number of tokens to generate in the completion. The token count of your prompt plus `max_tokens` cannot exceed the model's context length. | | diff --git a/packages/gcp/docs/sdks/fim/README.md b/packages/gcp/docs/sdks/fim/README.md index 61a28883..013f28dd 100644 --- a/packages/gcp/docs/sdks/fim/README.md +++ b/packages/gcp/docs/sdks/fim/README.md @@ -54,7 +54,7 @@ if res is not None: ### Response -**[Union[Generator[models.CompletionEvent, None, None], AsyncGenerator[models.CompletionEvent, None]]](../../models/.md)** +**Union[Generator[models.CompletionEvent, None, None], AsyncGenerator[models.CompletionEvent, None]]** ### Errors | Error Object | Status Code | Content Type | diff --git a/packages/gcp/pyproject.toml b/packages/gcp/pyproject.toml index dba8a772..9a8969c1 100644 --- a/packages/gcp/pyproject.toml +++ b/packages/gcp/pyproject.toml @@ -4,7 +4,7 @@ version = "2.0.0" description = "Python Client SDK for the Mistral AI API in GCP." authors = [{ name = "Mistral" }] requires-python = ">=3.10" -readme = "README.md" +readme = "README-PYPI.md" dependencies = [ "eval-type-backport >=0.2.0", "google-auth (>=2.31.0,<3.0.0)", diff --git a/packages/gcp/scripts/prepare_readme.py b/packages/gcp/scripts/prepare_readme.py index ae27b555..f73464c9 100644 --- a/packages/gcp/scripts/prepare_readme.py +++ b/packages/gcp/scripts/prepare_readme.py @@ -1,33 +1,45 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - import re import shutil +import sys + +GITHUB_URL = "https://github.com/mistralai/client-python.git" +BRANCH = "main" +REPO_SUBDIR = "packages/gcp" +LINK_PATTERN = re.compile(r"(\[[^\]]+\]\()((?![a-zA-Z][a-zA-Z0-9+.-]*:|#)[^\)]+)(\))") + + +def _build_base_url(repo_url: str, branch: str, repo_subdir: str) -> str: + normalized = repo_url[:-4] if repo_url.endswith(".git") else repo_url + subdir = repo_subdir.strip("/") + if subdir: + subdir = f"{subdir}/" + return f"{normalized}/blob/{branch}/{subdir}" + + +def _normalize_relative_path(path: str) -> str: + if path.startswith("./"): + path = path[2:] + elif path.startswith("/"): + path = path[1:] + return path + + +def _rewrite_relative_links(contents: str, base_url: str) -> str: + return LINK_PATTERN.sub( + lambda m: f"{m.group(1)}{base_url}{_normalize_relative_path(m.group(2))}{m.group(3)}", + contents, + ) + try: - with open("README.md", "r", encoding="utf-8") as rh: - readme_contents = rh.read() - GITHUB_URL = "https://github.com/mistralai/client-python.git" - GITHUB_URL = ( - GITHUB_URL[: -len(".git")] if GITHUB_URL.endswith(".git") else GITHUB_URL - ) - REPO_SUBDIR = "packages/gcp" - # Ensure the subdirectory has a trailing slash - if not REPO_SUBDIR.endswith("/"): - REPO_SUBDIR += "/" - # links on PyPI should have absolute URLs - readme_contents = re.sub( - r"(\[[^\]]+\]\()((?!https?:)[^\)]+)(\))", - lambda m: m.group(1) - + GITHUB_URL - + "/blob/master/" - + REPO_SUBDIR - + m.group(2) - + m.group(3), - readme_contents, - ) - - with open("README-PYPI.md", "w", encoding="utf-8") as wh: - wh.write(readme_contents) + with open("README.md", "r", encoding="utf-8") as fh: + readme_contents = fh.read() + + base_url = _build_base_url(GITHUB_URL, BRANCH, REPO_SUBDIR) + readme_contents = _rewrite_relative_links(readme_contents, base_url) + + with open("README-PYPI.md", "w", encoding="utf-8") as fh: + fh.write(readme_contents) except Exception as e: try: print("Failed to rewrite README.md to README-PYPI.md, copying original instead") @@ -36,3 +48,4 @@ except Exception as ie: print("Failed to copy README.md to README-PYPI.md") print(ie) + sys.exit(1) diff --git a/pyproject.toml b/pyproject.toml index 52251124..be5c7e6e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,10 +1,10 @@ [project] name = "mistralai" -version = "2.0.1" +version = "2.0.1.post1" description = "Python Client SDK for the Mistral AI API." authors = [{ name = "Mistral" }] requires-python = ">=3.10" -readme = "README.md" +readme = "README-PYPI.md" dependencies = [ "eval-type-backport >=0.2.0", "httpx >=0.28.1", diff --git a/scripts/prepare_readme.py b/scripts/prepare_readme.py index c220a055..7f7cfe74 100644 --- a/scripts/prepare_readme.py +++ b/scripts/prepare_readme.py @@ -1,107 +1,51 @@ -import argparse import re -import subprocess +import shutil import sys -from pathlib import Path -DEFAULT_REPO_URL = "https://github.com/mistralai/client-python.git" -DEFAULT_BRANCH = "main" -LINK_PATTERN = re.compile(r"(\[[^\]]+\]\()((?!https?:)[^\)]+)(\))") +GITHUB_URL = "https://github.com/mistralai/client-python.git" +BRANCH = "main" +REPO_SUBDIR = "" +LINK_PATTERN = re.compile(r"(\[[^\]]+\]\()((?![a-zA-Z][a-zA-Z0-9+.-]*:|#)[^\)]+)(\))") -def build_base_url(repo_url: str, branch: str, repo_subdir: str) -> str: - """Build the GitHub base URL used to rewrite relative README links.""" - normalized_repo_url = repo_url[:-4] if repo_url.endswith(".git") else repo_url - normalized_subdir = repo_subdir.strip("/") - if normalized_subdir: - normalized_subdir = f"{normalized_subdir}/" - return f"{normalized_repo_url}/blob/{branch}/{normalized_subdir}" +def _build_base_url(repo_url: str, branch: str, repo_subdir: str) -> str: + normalized = repo_url[:-4] if repo_url.endswith(".git") else repo_url + subdir = repo_subdir.strip("/") + if subdir: + subdir = f"{subdir}/" + return f"{normalized}/blob/{branch}/{subdir}" -def rewrite_relative_links(contents: str, base_url: str) -> str: - """Rewrite Markdown relative links to absolute GitHub URLs.""" - return LINK_PATTERN.sub( - lambda match: f"{match.group(1)}{base_url}{match.group(2)}{match.group(3)}", - contents, - ) - - -def run_with_rewritten_readme( - readme_path: Path, base_url: str, command: list[str] -) -> int: - """Rewrite README links, run a command, and restore the original README.""" - original_contents = readme_path.read_text(encoding="utf-8") - rewritten_contents = rewrite_relative_links(original_contents, base_url) - readme_path.write_text(rewritten_contents, encoding="utf-8") - try: - if not command: - return 0 - result = subprocess.run(command, check=False) - return result.returncode - finally: - readme_path.write_text(original_contents, encoding="utf-8") +def _normalize_relative_path(path: str) -> str: + if path.startswith("./"): + path = path[2:] + elif path.startswith("/"): + path = path[1:] + return path -def parse_args(argv: list[str]) -> argparse.Namespace: - """Parse command-line arguments for README rewriting.""" - parser = argparse.ArgumentParser( - description=( - "Rewrite README links to absolute GitHub URLs while running a command." - ) - ) - parser.add_argument( - "--readme", - type=Path, - default=Path("README.md"), - help="Path to the README file to rewrite.", - ) - parser.add_argument( - "--repo-url", - default=DEFAULT_REPO_URL, - help="Repository URL used to build absolute links.", - ) - parser.add_argument( - "--branch", - default=DEFAULT_BRANCH, - help="Repository branch used for absolute links.", - ) - parser.add_argument( - "--repo-subdir", - default="", - help="Repository subdirectory that contains the README.", - ) - parser.add_argument( - "command", - nargs=argparse.REMAINDER, - help=( - "Command to run (prefix with -- to stop option parsing). " - "If omitted, the rewritten README is printed to stdout." - ), +def _rewrite_relative_links(contents: str, base_url: str) -> str: + return LINK_PATTERN.sub( + lambda m: f"{m.group(1)}{base_url}{_normalize_relative_path(m.group(2))}{m.group(3)}", + contents, ) - return parser.parse_args(argv) -def main(argv: list[str]) -> int: - """Entry point for rewriting README links during build commands.""" - args = parse_args(argv) - readme_path = args.readme - if not readme_path.is_file(): - raise FileNotFoundError(f"README file not found: {readme_path}") - base_url = build_base_url(args.repo_url, args.branch, args.repo_subdir) - command = ( - args.command[1:] - if args.command and args.command[0] == "--" - else args.command - ) - if not command: - rewritten_contents = rewrite_relative_links( - readme_path.read_text(encoding="utf-8"), - base_url, - ) - sys.stdout.write(rewritten_contents) - return 0 - return run_with_rewritten_readme(readme_path, base_url, command) +try: + with open("README.md", "r", encoding="utf-8") as fh: + readme_contents = fh.read() + base_url = _build_base_url(GITHUB_URL, BRANCH, REPO_SUBDIR) + readme_contents = _rewrite_relative_links(readme_contents, base_url) -if __name__ == "__main__": - sys.exit(main(sys.argv[1:])) + with open("README-PYPI.md", "w", encoding="utf-8") as fh: + fh.write(readme_contents) +except Exception as e: + try: + print("Failed to rewrite README.md to README-PYPI.md, copying original instead") + print(e) + shutil.copyfile("README.md", "README-PYPI.md") + except Exception as ie: + print("Failed to copy README.md to README-PYPI.md") + print(ie) + sys.exit(1) diff --git a/src/mistralai/extra/README.md b/src/mistralai/extra/README.md index 0593d84a..94f077f7 100644 --- a/src/mistralai/extra/README.md +++ b/src/mistralai/extra/README.md @@ -34,13 +34,13 @@ class Chat(BaseSDK): 3. Now build the SDK with the custom code: ```bash -rm -rf dist; uv build; uv pip install --reinstall ~/client-python/dist/mistralai-1.4.1-py3-none-any.whl +rm -rf dist; uv build; uv pip install --reinstall ~/client-python/dist/mistralai-2.0.0-py3-none-any.whl ``` 4. And now you should be able to call the custom method: ```python import os -from mistralai import Mistral +from mistralai.client import Mistral api_key = os.environ["MISTRAL_API_KEY"] client = Mistral(api_key=api_key) diff --git a/tests/test_prepare_readme.py b/tests/test_prepare_readme.py index ce3e11c9..76227ae4 100644 --- a/tests/test_prepare_readme.py +++ b/tests/test_prepare_readme.py @@ -1,6 +1,8 @@ import importlib.util from pathlib import Path +import pytest + SCRIPT_PATH = Path(__file__).resolve().parents[1] / "scripts" / "prepare_readme.py" SPEC = importlib.util.spec_from_file_location("prepare_readme", SCRIPT_PATH) if SPEC is None or SPEC.loader is None: @@ -8,30 +10,83 @@ prepare_readme = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(prepare_readme) +BASE_URL = "https://example.com/blob/main/" + def test_rewrite_relative_links_keeps_absolute() -> None: - base_url = "https://example.com/blob/main/" contents = "[Migration](MIGRATION.md)\n[Docs](https://docs.mistral.ai)" expected = ( - "[Migration](https://example.com/blob/main/MIGRATION.md)\n" + f"[Migration]({BASE_URL}MIGRATION.md)\n" "[Docs](https://docs.mistral.ai)" ) - assert prepare_readme.rewrite_relative_links(contents, base_url) == expected + assert prepare_readme._rewrite_relative_links(contents, BASE_URL) == expected + + +def test_rewrite_relative_links_keeps_http() -> None: + contents = "[Site](http://example.com)" + assert prepare_readme._rewrite_relative_links(contents, BASE_URL) == contents -def test_main_prints_rewritten_readme_with_defaults(tmp_path, capsys) -> None: - original = "[Migration](MIGRATION.md)\n" - base_url = prepare_readme.build_base_url( - prepare_readme.DEFAULT_REPO_URL, - prepare_readme.DEFAULT_BRANCH, - "", +def test_rewrite_relative_links_keeps_anchors() -> None: + contents = "[Retries](#retries)\n[File](docs/README.md#upload)" + expected = ( + "[Retries](#retries)\n" + f"[File]({BASE_URL}docs/README.md#upload)" ) - expected = f"[Migration]({base_url}MIGRATION.md)\n" - readme_path = tmp_path / "README.md" - readme_path.write_text(original, encoding="utf-8") + assert prepare_readme._rewrite_relative_links(contents, BASE_URL) == expected + + +def test_rewrite_relative_links_keeps_mailto() -> None: + contents = "[Email](mailto:user@example.com)" + assert prepare_readme._rewrite_relative_links(contents, BASE_URL) == contents + + +def test_rewrite_relative_links_keeps_ftp() -> None: + contents = "[FTP](ftp://files.example.com/data)" + assert prepare_readme._rewrite_relative_links(contents, BASE_URL) == contents + + +def test_rewrite_strips_leading_dot_slash() -> None: + contents = "[Errors](./src/errors.py)" + expected = f"[Errors]({BASE_URL}src/errors.py)" + assert prepare_readme._rewrite_relative_links(contents, BASE_URL) == expected + + +def test_rewrite_strips_leading_slash() -> None: + contents = "[Examples](/examples/azure)" + expected = f"[Examples]({BASE_URL}examples/azure)" + assert prepare_readme._rewrite_relative_links(contents, BASE_URL) == expected - exit_code = prepare_readme.main(["--readme", str(readme_path)]) - captured = capsys.readouterr() - assert exit_code == 0 - assert captured.out == expected +def test_rewrite_multiple_links_same_line() -> None: + contents = "[A](a.md) and [B](b.md)" + expected = f"[A]({BASE_URL}a.md) and [B]({BASE_URL}b.md)" + assert prepare_readme._rewrite_relative_links(contents, BASE_URL) == expected + + +def test_build_base_url_strips_git_suffix() -> None: + url = prepare_readme._build_base_url( + "https://github.com/org/repo.git", "main", "" + ) + assert url == "https://github.com/org/repo/blob/main/" + + +def test_build_base_url_no_git_suffix() -> None: + url = prepare_readme._build_base_url( + "https://github.com/org/repo", "main", "" + ) + assert url == "https://github.com/org/repo/blob/main/" + + +def test_build_base_url_with_subdir() -> None: + url = prepare_readme._build_base_url( + "https://github.com/org/repo.git", "main", "packages/azure" + ) + assert url == "https://github.com/org/repo/blob/main/packages/azure/" + + +def test_build_base_url_strips_subdir_slashes() -> None: + url = prepare_readme._build_base_url( + "https://github.com/org/repo.git", "main", "/packages/azure/" + ) + assert url == "https://github.com/org/repo/blob/main/packages/azure/" diff --git a/uv.lock b/uv.lock index 9a01d8e6..a431998a 100644 --- a/uv.lock +++ b/uv.lock @@ -551,7 +551,7 @@ wheels = [ [[package]] name = "mistralai" -version = "2.0.1" +version = "2.0.1.post1" source = { editable = "." } dependencies = [ { name = "eval-type-backport" },