### Building and Installing the SDK with Custom Code Source: https://github.com/mistralai/client-python/blob/main/src/mistralai/extra/README.md After adding custom code, build the SDK and install it locally. This command sequence removes the existing distribution, builds a new one, and then installs the newly built wheel file. ```bash rm -rf dist; uv build; uv pip install --reinstall ~/client-python/dist/mistralai-2.0.0-py3-none-any.whl ``` -------------------------------- ### Install Mistral Python Client Source: https://github.com/mistralai/client-python/blob/main/packages/azure/README.md Install the Mistral AI Python client using pip or uv. ```bash pip install mistralai ``` ```bash uv add mistralai ``` -------------------------------- ### Install Mistral AI GCP Extras Source: https://github.com/mistralai/client-python/blob/main/packages/gcp/README-PYPI.md Install the Mistral AI Python client with the necessary extras for Google Cloud Platform integration. ```bash pip install mistralai[gcp] ``` -------------------------------- ### Install Mistral AI GCP Client Source: https://github.com/mistralai/client-python/blob/main/packages/gcp/README.md Install the Mistral AI Python client with the necessary extras for Google Cloud integration. ```bash pip install mistralai[gcp] ``` -------------------------------- ### Install Mistral AI Python SDK with GCP Support Source: https://github.com/mistralai/client-python/blob/main/README.md Install the Mistral AI Python SDK along with the necessary dependencies for Google Cloud Platform authentication. ```bash pip install mistralai # For GCP authentication support (required): pip install "mistralai[gcp]" ``` -------------------------------- ### Install Mistral AI SDK with pip Source: https://github.com/mistralai/client-python/blob/main/README.md Use this command to install the mistralai package using the pip package manager. ```bash pip install mistralai ``` -------------------------------- ### Install Mistral AI SDK with agents extra Source: https://github.com/mistralai/client-python/blob/main/README.md Install the mistralai package with the 'agents' extra dependencies to enable agent-related features. Requires Python 3.10+. ```bash pip install "mistralai[agents]" ``` -------------------------------- ### ModerationLLMAction Example Usage Source: https://github.com/mistralai/client-python/blob/main/packages/gcp/docs/models/moderationllmaction.md Demonstrates how to import and assign a value to ModerationLLMAction. The 'none' value is used as an example. ```python from mistralai.gcp.client.models import ModerationLLMAction value: ModerationLLMAction = "none" ``` -------------------------------- ### Azure AI Chat Completion Example Source: https://github.com/mistralai/client-python/blob/main/README.md Example of how to perform a chat completion using the Mistral AI SDK with Azure AI. Ensure AZURE_API_KEY, AZURE_ENDPOINT, and AZURE_MODEL environment variables are set. ```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 Chat Completion Example Source: https://github.com/mistralai/client-python/blob/main/README.md Example of how to perform a chat completion using the Mistral AI SDK with Google Cloud Vertex AI. The SDK automatically detects credentials and builds the Vertex AI URL. ```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) ``` -------------------------------- ### JobsAPIRoutesFineTuningStartFineTuningJobRequest Source: https://github.com/mistralai/client-python/blob/main/docs/models/jobsapiroutesfinetuningstartfinetuningjobrequest.md Defines the request body structure for starting a fine-tuning job. ```APIDOC ## POST /v1/fine-tuning/jobs ### Description Starts a new fine-tuning job. ### Method POST ### Endpoint /v1/fine-tuning/jobs ### Request Body - **job_id** (str) - Required - The ID of the fine-tuning job. ### Request Example { "job_id": "ft-j-xxxxxxxxxxxxxxxxx" } ### Response #### Success Response (200) - **id** (str) - The unique identifier for the fine-tuning job. - **object** (str) - The type of object, e.g., "fine_tuning.job". - **created_at** (int) - Unix timestamp of job creation. - **error** (object) - Details about any errors encountered during job creation. - **fine_tuned_model** (str) - The name of the fine-tuned model (if applicable). - **model** (str) - The base model used for fine-tuning. - **object** (str) - The type of object, e.g., "fine_tuning.job". - **result_files** (array) - List of file IDs for the results. - **status** (str) - The current status of the job (e.g., "validating_files", "queued", "running", "succeeded", "failed", "cancelled"). - **trained_tokens** (int) - The number of tokens trained. - **tuning_file** (str) - The ID of the training file. - **updated_at** (int) - Unix timestamp of the last update. - **validation_file** (str) - The ID of the validation file. #### Response Example { "id": "ft-j-xxxxxxxxxxxxxxxxx", "object": "fine_tuning.job", "created_at": 1699000000, "error": null, "fine_tuned_model": null, "model": "gpt-3.5-turbo", "result_files": [], "status": "validating_files", "trained_tokens": 0, "tuning_file": "file-xxxxxxxxxxxxxxxxx", "updated_at": 1699000000, "validation_file": null } ``` -------------------------------- ### Initialize ToolExecutionStartedEvent Source: https://github.com/mistralai/client-python/blob/main/docs/models/conversationeventsdata.md Represents the start of a tool execution. ```python value: models.ToolExecutionStartedEvent = /* values here */ ``` -------------------------------- ### Get Connector by ID or Name Source: https://github.com/mistralai/client-python/blob/main/docs/sdks/connectors/README.md Use this snippet to retrieve a connector using its ID or name. It demonstrates how to initialize the Mistral client and make the GET request, with options to fetch associated user and customer data. Ensure the MISTRAL_API_KEY environment variable is set. ```python from mistralai.client import Mistral import os with Mistral( api_key=os.getenv("MISTRAL_API_KEY", ""), ) as mistral: res = mistral.beta.connectors.get(connector_id_or_name="", fetch_user_data=False, fetch_customer_data=False) # Handle response print(res) ``` -------------------------------- ### Get Connector Source: https://github.com/mistralai/client-python/blob/main/docs/sdks/connectors/README.md Retrieves details of a specific connector. ```APIDOC ## get connector ### Description Get a connector. ### Method GET ### Endpoint /connectors/{connector_id} ### Parameters #### Path Parameters - **connector_id** (string) - Required - The ID of the connector. ``` -------------------------------- ### GET /v1/workflows/{workflow_name}/metrics Source: https://github.com/mistralai/client-python/blob/main/docs/sdks/metrics/README.md Retrieves comprehensive metrics for a specified workflow. You can filter metrics by providing optional start and end times in ISO 8601 format. ```APIDOC ## GET /v1/workflows/{workflow_name}/metrics ### Description Get comprehensive metrics for a specific workflow. ### Method GET ### Endpoint /v1/workflows/{workflow_name}/metrics ### Parameters #### Path Parameters - **workflow_name** (str) - Required - The name of the workflow type to get metrics for. #### Query Parameters - **start_time** (date) - Optional - Filter workflows started after this time (ISO 8601). - **end_time** (date) - Optional - Filter workflows started before this time (ISO 8601). - **retries** (Optional[utils.RetryConfig]) - Optional - Configuration to override the default retry behavior of the client. ### Request Example ```json { "example": "GET /v1/workflows/MyWorkflow/metrics" } ``` ### Response #### Success Response (200) - **execution_count** (int) - Total number of executions. - **success_count** (int) - Number of successful executions. - **error_count** (int) - Number of failed/terminated executions. - **average_latency_ms** (float) - Average execution duration in milliseconds. - **retry_rate** (float) - Proportion of workflows with retries. - **latency_over_time** (dict) - Time-series data of execution durations. #### Response Example ```json { "example": "{\"execution_count\": 100, \"success_count\": 90, \"error_count\": 10, \"average_latency_ms\": 1500.5, \"retry_rate\": 0.1, \"latency_over_time\": {}}" } ``` ### Errors - **errors.HTTPValidationError** (422) - application/json - **errors.SDKError** (4XX, 5XX) - */* ``` -------------------------------- ### Initialize SDK with Custom httpx.Client Source: https://github.com/mistralai/client-python/blob/main/packages/gcp/README.md Configure the SDK client with a custom httpx.Client instance to set default headers for all requests. Ensure httpx is installed. ```python import os from mistralai.gcp.client import MistralGCP import httpx http_client = httpx.Client(headers={"x-custom-header": "someValue"}) s = MistralGCP( project_id=os.environ.get("GCP_PROJECT_ID"), region="us-central1", client=http_client, ) ``` -------------------------------- ### Append Messages to a Conversation using Python SDK Source: https://github.com/mistralai/client-python/blob/main/docs/sdks/conversations/README.md This example shows how to append user entries to an existing conversation and get a new completion. It demonstrates setting response format and handling the response. ```python from mistralai.client import Mistral import os with Mistral( api_key=os.getenv("MISTRAL_API_KEY", ""), ) as mistral: res = mistral.beta.conversations.append(conversation_id="", store=True, handoff_execution="server", completion_args={ "response_format": { "type": "text", }, }) # Handle response print(res) ``` -------------------------------- ### Initialize SDK with Custom HTTP Client Headers Source: https://github.com/mistralai/client-python/blob/main/packages/azure/README.md Configure a custom HTTP client with specific headers to be sent with every SDK request. This example uses `httpx.Client` for synchronous operations. ```python from mistralai.azure.client import MistralAzure import httpx import os http_client = httpx.Client(headers={"x-custom-header": "someValue"}) s = MistralAzure( api_key=os.environ["AZURE_API_KEY"], server_url=os.environ["AZURE_ENDPOINT"], api_version=os.environ.get("AZURE_API_VERSION", "2024-05-01-preview"), client=http_client, ) ``` -------------------------------- ### Install additional mistralai packages Source: https://github.com/mistralai/client-python/blob/main/README.md Install supplementary mistralai packages, such as mistralai-workflows, which are available under the mistralai namespace. ```bash pip install mistralai-workflows ``` -------------------------------- ### Initialize SDK with API Key and Server URL Source: https://github.com/mistralai/client-python/blob/main/packages/azure/README.md Instantiate the Mistral Azure client using your API key and server URL. The SDK automatically handles the `api-version` query parameter. This is the standard way to authenticate and configure the client for Azure endpoints. ```python from mistralai.azure.client import MistralAzure import os s = MistralAzure( api_key=os.environ["AZURE_API_KEY"], server_url=os.environ["AZURE_ENDPOINT"], api_version=os.environ.get("AZURE_API_VERSION", "2024-05-01-preview"), ) res = s.chat.stream( messages=[ { "role": "user", "content": "Who is the best French painter? Answer in one short sentence.", }, ], model=os.environ["AZURE_MODEL"], ) if res is not None: for event in res: # handle event print(event) ``` -------------------------------- ### Create and Start a New Campaign Source: https://github.com/mistralai/client-python/blob/main/docs/sdks/campaigns/README.md Use this snippet to create and initiate a new campaign. Ensure you provide all required parameters like search_params, judge_id, name, description, and max_nb_events. The API key should be set via the MISTRAL_API_KEY environment variable. ```python from mistralai.client import Mistral import os with Mistral( api_key=os.getenv("MISTRAL_API_KEY", ""), ) as mistral: res = mistral.beta.observability.campaigns.create(search_params={ "filters": { "field": "", "op": "lt", "value": "", }, }, judge_id="9b501b9f-3525-44a7-a51a-5352679be9ed", name="", description="shakily triangular scotch requirement whether once oh", max_nb_events=232889) # Handle response print(res) ``` -------------------------------- ### Get Index Schema Detail Request Source: https://github.com/mistralai/client-python/blob/main/docs/models/getindexschemadetailv1ragindexesindexindexidschemasschemaschemaiddetailgetrequest.md This snippet shows the structure of a request to get the index schema detail. ```APIDOC ## GET /v1/rag/indexes/{index_id}/schemas/{schema_id}/detail ### Description Retrieves the detailed schema for a specific index and schema ID. ### Method GET ### Endpoint /v1/rag/indexes/{index_id}/schemas/{schema_id}/detail ### Parameters #### Path Parameters - **index_id** (str) - Required - The ID of the index. - **schema_id** (str) - Required - The ID of the schema. ### Response #### Success Response (200) - **schema_detail** (object) - The detailed schema information. ``` -------------------------------- ### Instantiate ReasoningEffort Source: https://github.com/mistralai/client-python/blob/main/packages/gcp/docs/models/reasoningeffort.md Demonstrates how to instantiate the ReasoningEffort model with a value. The model accepts predefined string literals. ```python from mistralai.gcp.client.models import ReasoningEffort value: ReasoningEffort = "none" ``` -------------------------------- ### Define Response Format Examples Source: https://github.com/mistralai/client-python/blob/main/docs/models/completionargs.md Examples of JSON structures for defining text, JSON object, and JSON schema response formats. ```json { "type": "text" } ``` ```json { "type": "json_object" } ``` ```json { "type": "json_schema", "json_schema": { "schema": { "properties": { "name": { "title": "Name", "type": "string" }, "authors": { "items": { "type": "string" }, "title": "Authors", "type": "array" } }, "required": [ "name", "authors" ], "title": "Book", "type": "object", "additionalProperties": false }, "name": "book", "strict": true } } ``` -------------------------------- ### Upload a File (Synchronous) Source: https://github.com/mistralai/client-python/blob/main/README.md This snippet demonstrates synchronous file upload. Ensure the file 'example.file' exists and the MISTRAL_API_KEY is set. ```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) ``` -------------------------------- ### Initialize Azure Client with Custom HTTP Client Source: https://github.com/mistralai/client-python/blob/main/packages/azure/README-PYPI.md Integrate a custom `httpx.Client` instance to configure timeouts, headers, and other low-level network settings for all SDK requests. ```python from mistralai.azure.client import MistralAzure import httpx import os http_client = httpx.Client(headers={"x-custom-header": "someValue"}) s = MistralAzure( api_key=os.environ["AZURE_API_KEY"], server_url=os.environ["AZURE_ENDPOINT"], api_version=os.environ.get("AZURE_API_VERSION", "2024-05-01-preview"), client=http_client, ) ``` -------------------------------- ### Initialize CompletionFineTuningJobDetailsStatus Source: https://github.com/mistralai/client-python/blob/main/docs/models/completionfinetuningjobdetailsstatus.md Demonstrates how to import and assign a value to CompletionFineTuningJobDetailsStatus. Unrecognized values are captured as UnrecognizedStr. ```python from mistralai.client.models import CompletionFineTuningJobDetailsStatus # Open enum: unrecognized values are captured as UnrecognizedStr value: CompletionFineTuningJobDetailsStatus = "QUEUED" ``` -------------------------------- ### POST /v1/observability/datasets/{dataset_id}/imports/from-explorer Source: https://github.com/mistralai/client-python/blob/main/docs/sdks/datasets/README.md Populates a dataset with samples selected from the explorer. ```APIDOC ## POST /v1/observability/datasets/{dataset_id}/imports/from-explorer ### Description Populates the dataset with samples from the explorer. ### Method POST ### Endpoint /v1/observability/datasets/{dataset_id}/imports/from-explorer ### Parameters #### Path Parameters - **dataset_id** (str) - Required - The ID of the dataset to import into. #### Query Parameters - **completion_event_ids** (list[str]) - Required - A list of completion event IDs to import from the explorer. #### Request Body None ### Request Example ```python from mistralai.client import Mistral import os with Mistral( api_key=os.getenv("MISTRAL_API_KEY", ""), ) as mistral: res = mistral.beta.observability.datasets.import_from_explorer(dataset_id="ee1930e9-54f7-4c68-aa8a-40fe5d2a3485", completion_event_ids=[ "", "", "", ]) # Handle response print(res) ``` ### Response #### Success Response (200) - **DatasetImportTask** (models.DatasetImportTask) - Details of the dataset import task. #### Response Example ```json { "example": "response body" } ``` ### Errors - **errors.ObservabilityError**: Status Code 400, 404, 408, 409, 422, Content Type application/json - **errors.SDKError**: Status Code 4XX, 5XX, Content Type */* ``` -------------------------------- ### Initialize MistralGCP Client Source: https://github.com/mistralai/client-python/blob/main/packages/gcp/README.md The SDK automatically constructs the Vertex AI endpoint using the provided project_id and region. ```python import os from mistralai.gcp.client import MistralGCP # The SDK auto-detects credentials and builds the Vertex AI URL s = MistralGCP( project_id=os.environ.get("GCP_PROJECT_ID"), # Optional: auto-detected region=os.environ.get("GCP_REGION", "us-central1"), ) res = s.chat.stream( messages=[ { "role": "user", "content": "Who is the best French painter? Answer in one short sentence.", }, ], model="mistral-small-2503", ) if res is not None: for event in res: # handle event print(event) ``` -------------------------------- ### Agents Completion Request Message Example Source: https://github.com/mistralai/client-python/blob/main/docs/models/agentscompletionrequest.md This example shows the structure of a message object within the 'messages' list for an Agents Completion Request. It includes the role and content of the prompt. ```python { "role": "user", "content": "Who is the best French painter? Answer in one short sentence." } ``` -------------------------------- ### models.Tool Example Source: https://github.com/mistralai/client-python/blob/main/packages/azure/docs/models/chatcompletionrequesttool.md Represents a generic tool definition. Use this as a base or for custom tool implementations. ```python value: models.Tool = /* values here */ ``` -------------------------------- ### Get Connector Authentication Methods Source: https://github.com/mistralai/client-python/blob/main/docs/sdks/connectors/README.md Retrieves the authentication methods supported by a connector. ```APIDOC ## get_authentication_methods connector ### Description Get authentication methods for a connector. ### Method GET ### Endpoint /connectors/{connector_id}/auth-methods ### Parameters #### Path Parameters - **connector_id** (string) - Required - The ID of the connector. ``` -------------------------------- ### Get Specific Conversation by ID with Python SDK Source: https://github.com/mistralai/client-python/blob/main/docs/sdks/conversations/README.md Retrieve a single conversation entity using its unique ID. Ensure the Mistral client is initialized and provide the `conversation_id` to the `get` method. The `conversation_id` is a required parameter. ```python from mistralai.client import Mistral import os with Mistral( api_key=os.getenv("MISTRAL_API_KEY", ""), ) as mistral: res = mistral.beta.conversations.get(conversation_id="") # Handle response print(res) ``` -------------------------------- ### stream_workflow_execution_logs Source: https://github.com/mistralai/client-python/blob/main/docs/sdks/executions/README.md Stream logs for a workflow execution via SSE. This method allows for resuming streams from a specific point using `last_event_id` or starting from a timestamp with `after`. If neither is provided, it tails logs from the execution's start. ```APIDOC ## stream_workflow_execution_logs Stream logs for a workflow execution via SSE. If `last_event_id` is set it resumes from that cursor and takes precedence over `after`; otherwise `after` sets a fresh stream's start point (omit both to tail from the execution start). ### Parameters #### Path Parameters - **execution_id** (str) - Required - The ID of the workflow execution. #### Query Parameters - **run_id** (Optional[str]) - Optional - Filter logs by workflow run ID. - **activity_id** (Optional[str]) - Optional - Filter logs by activity ID. - **after** (date) - Optional - Start a fresh stream at this timestamp (ignored when resuming via last_event_id). - **last_event_id** (Optional[str]) - Optional - Resume from this cursor (a prior response's SSE id). #### Request Body This endpoint does not accept a request body. ### Response **Union[eventstreaming.EventStream[models.StreamWorkflowExecutionLogsResponseBody], eventstreaming.EventStreamAsync[models.StreamWorkflowExecutionLogsResponseBody]]** ### Errors - **errors.HTTPValidationError**: Status Code 422, Content Type application/json - **errors.SDKError**: Status Code 4XX, 5XX, Content Type */* ``` -------------------------------- ### Python Confirmation Model Usage Source: https://github.com/mistralai/client-python/blob/main/docs/models/confirmation.md Demonstrates how to use the Confirmation model with allowed values. ```python from mistralai.client.models import Confirmation value: Confirmation = "allow" ``` -------------------------------- ### Update Connector Example Source: https://github.com/mistralai/client-python/blob/main/docs/sdks/connectors/README.md Use this snippet to update a connector by its ID. Ensure you have your MISTRAL_API_KEY set in your environment variables. The connector_id is required. ```python from mistralai.client import Mistral import os with Mistral( api_key=os.getenv("MISTRAL_API_KEY", ""), ) as mistral: res = mistral.beta.connectors.update(connector_id="81d30634-113f-4dce-a89e-7786be2d8693") # Handle response print(res) ``` -------------------------------- ### Get Connector Authentication URL Source: https://github.com/mistralai/client-python/blob/main/docs/sdks/connectors/README.md Retrieves the authentication URL for a specific connector. ```APIDOC ## get_auth_url connector ### Description Get the auth URL for a connector. ### Method GET ### Endpoint /connectors/{connector_id}/auth-url ### Parameters #### Path Parameters - **connector_id** (string) - Required - The ID of the connector. ``` -------------------------------- ### Initialize Mistral Client with Custom HTTP Client Source: https://github.com/mistralai/client-python/blob/main/README-PYPI.md Configure the SDK client with a custom `httpx.Client` instance to manage timeouts, cookies, proxies, and headers. ```python from mistralai.client import Mistral import httpx http_client = httpx.Client(headers={"x-custom-header": "someValue"}) s = Mistral(client=http_client) ``` -------------------------------- ### get_auth_url Source: https://github.com/mistralai/client-python/blob/main/docs/sdks/connectors/README.md Get the OAuth2 authorization URL for a connector to initiate user authentication. ```APIDOC ## get_auth_url ### Description Get the OAuth2 authorization URL for a connector to initiate user authentication. ### Method GET ### Endpoint /v1/connectors/{connector_id_or_name}/auth_url ### Parameters #### Path Parameters - **connector_id_or_name** (string) - Required - The ID or name of the connector. #### Query Parameters - **github_installation_link** (boolean) - Optional - If true, returns a GitHub installation link. ### Request Example ```python from mistralai.client import Mistral import os with Mistral( api_key=os.getenv("MISTRAL_API_KEY", ""), ) as mistral: res = mistral.beta.connectors.get_auth_url(connector_id_or_name="", github_installation_link=False) # Handle response print(res) ``` ### Response #### Success Response (200) - **auth_url** (string) - The authorization URL for the connector. #### Response Example ```json { "auth_url": "https://example.com/oauth/authorize?client_id=..." } ``` ``` -------------------------------- ### Get Voice Details with Mistral AI SDK Source: https://github.com/mistralai/client-python/blob/main/docs/sdks/voices/README.md Use this snippet to retrieve details for a specific voice by its ID. Ensure you have your MISTRAL_API_KEY set in your environment variables. The client is initialized and then used to call the `get` method on the `voices` object. ```python from mistralai.client import Mistral import os with Mistral( api_key=os.getenv("MISTRAL_API_KEY", ""), ) as mistral: res = mistral.audio.voices.get(voice_id="") # Handle response print(res) ``` -------------------------------- ### Start a fine-tuning job Source: https://github.com/mistralai/client-python/blob/main/docs/sdks/finetuningjobs/README.md Uses the fine_tuning.jobs.start method to initiate a validated fine-tuning job. ```python from mistralai.client import Mistral import os with Mistral( api_key=os.getenv("MISTRAL_API_KEY", ""), ) as mistral: res = mistral.fine_tuning.jobs.start(job_id="56553e4d-0679-471e-b9ac-59a77d671103") # Handle response print(res) ``` -------------------------------- ### TempoTraceAttributeArrayValue Example Source: https://github.com/mistralai/client-python/blob/main/docs/models/tempotraceattributevalue.md Assign an array value to a TempoTraceAttributeValue. ```python value: models.TempoTraceAttributeArrayValue = /* values here */ ``` -------------------------------- ### Initialize Mistral Azure Client and Complete Chat Source: https://github.com/mistralai/client-python/blob/main/packages/azure/docs/sdks/chat/README.md Demonstrates how to initialize the MistralAzure client with API key, endpoint, and model, then use it to complete a chat conversation. Ensure environment variables for API key, endpoint, and model are set. ```python from mistralai.azure.client import MistralAzure import os AZURE_API_KEY = os.environ["AZURE_API_KEY"] AZURE_ENDPOINT = os.environ["AZURE_ENDPOINT"] AZURE_MODEL = os.environ["AZURE_MODEL"] AZURE_API_VERSION = os.environ.get("AZURE_API_VERSION", "2024-05-01-preview") # The SDK automatically injects api-version as a query parameter s = MistralAzure( api_key=AZURE_API_KEY, server_url=AZURE_ENDPOINT, api_version=AZURE_API_VERSION, ) res = s.chat.complete(messages=[ { "role": "user", "content": "Who is the best French painter? Answer in one short sentence.", }, ], model=AZURE_MODEL) if res is not None: # handle response print(res.choices[0].message.content) ``` -------------------------------- ### TempoTraceAttributeBoolValue Example Source: https://github.com/mistralai/client-python/blob/main/docs/models/tempotraceattributevalue.md Assign a boolean value to a TempoTraceAttributeValue. ```python value: models.TempoTraceAttributeBoolValue = /* values here */ ``` -------------------------------- ### Using ProcessStatus Enum Source: https://github.com/mistralai/client-python/blob/main/docs/models/processstatus.md Demonstrates how to import and use the ProcessStatus enum. Unrecognized string values are handled gracefully. ```python from mistralai.client.models import ProcessStatus # Open enum: unrecognized values are captured as UnrecognizedStr value: ProcessStatus = "self_managed" ``` -------------------------------- ### Get Connector Authentication Methods Source: https://github.com/mistralai/client-python/blob/main/docs/sdks/connectors/README.md Retrieve the authentication schema for a specified connector. This includes the list of supported authentication methods and their required headers. Ensure the MISTRAL_API_KEY environment variable is set. ```python from mistralai.client import Mistral import os with Mistral( api_key=os.getenv("MISTRAL_API_KEY", ""), ) as mistral: res = mistral.beta.connectors.get_authentication_methods(connector_id_or_name="") # Handle response print(res) ``` -------------------------------- ### TempoTraceAttributeIntValue Example Source: https://github.com/mistralai/client-python/blob/main/docs/models/tempotraceattributevalue.md Assign an integer value to a TempoTraceAttributeValue. ```python value: models.TempoTraceAttributeIntValue = /* values here */ ``` -------------------------------- ### Install Mistral AI SDK with uv Source: https://github.com/mistralai/client-python/blob/main/README.md Use this command to add the mistralai package to your project when using the uv package manager. ```bash uv add mistralai ``` -------------------------------- ### Configure Server URL with Mistral AI GCP Client Source: https://github.com/mistralai/client-python/blob/main/packages/gcp/README-PYPI.md Shows how to initialize the MistralGCP client, which automatically constructs the Vertex AI endpoint using project ID and region. This snippet also demonstrates streaming chat completions. ```python import os from mistralai.gcp.client import MistralGCP # The SDK auto-detects credentials and builds the Vertex AI URL s = MistralGCP( project_id=os.environ.get("GCP_PROJECT_ID"), # Optional: auto-detected region=os.environ.get("GCP_REGION", "us-central1"), ) res = s.chat.stream( messages=[ { "role": "user", "content": "Who is the best French painter? Answer in one short sentence.", }, ], model="mistral-small-2503", ) if res is not None: for event in res: # handle event print(event) ``` -------------------------------- ### TempoTraceAttributeStringValue Example Source: https://github.com/mistralai/client-python/blob/main/docs/models/tempotraceattributevalue.md Assign a string value to a TempoTraceAttributeValue. ```python value: models.TempoTraceAttributeStringValue = /* values here */ ``` -------------------------------- ### Initialize SystemMessage Source: https://github.com/mistralai/client-python/blob/main/docs/models/agentscompletionrequestmessage.md Use this model to define system-level instructions for the agent. ```python value: models.SystemMessage = /* values here */ ``` -------------------------------- ### get Source: https://github.com/mistralai/client-python/blob/main/docs/sdks/documents/README.md Retrieve the metadata of a specific document by its ID. ```APIDOC ## get ### Description Retrieve the metadata of a specific document by its ID. ### Method GET ### Endpoint /v1/libraries/{library_id}/documents/{document_id} ### Parameters #### Path Parameters - **library_id** (str) - Required - The ID of the library containing the document. - **document_id** (str) - Required - The ID of the document to retrieve. ### Request Example ```python from mistralai.client import Mistral import os with Mistral( api_key=os.getenv("MISTRAL_API_KEY", ""), ) as mistral: res = mistral.beta.libraries.documents.get(library_id="5c3ca4cd-62bc-4c71-ad8a-1531ae80d078", document_id="doc_id_1") # Handle response print(res) ``` ### Response #### Success Response (200) - **id** (str) - The ID of the document. - **library_id** (str) - The ID of the library the document belongs to. - **name** (str) - The name of the document. - **status** (str) - The processing status of the document. - **created_at** (str) - The timestamp when the document was created. - **metadata** (dict) - The metadata associated with the document. #### Response Example ```json { "id": "doc_id_1", "library_id": "lib_id_1", "name": "my_document.pdf", "status": "processed", "created_at": "2023-01-01T10:00:00Z", "metadata": {"key": "value"} } ``` ``` -------------------------------- ### Get Connector Authorization URL Source: https://github.com/mistralai/client-python/blob/main/docs/sdks/connectors/README.md Use this to obtain the OAuth2 authorization URL for a connector. This initiates the user authentication process for the connector. ```python from mistralai.client import Mistral import os with Mistral( api_key=os.getenv("MISTRAL_API_KEY", ""), ) as mistral: res = mistral.beta.connectors.get_auth_url(connector_id_or_name="", github_installation_link=False) # Handle response print(res) ``` -------------------------------- ### Get Connector Source: https://github.com/mistralai/client-python/blob/main/docs/sdks/connectors/README.md Retrieves a specific connector by its unique identifier (ID or name). It allows optional fetching of associated user and customer data. ```APIDOC ## GET /v1/connectors/{connector_id_or_name} ### Description Get a connector by its ID or name. This operation allows for optional retrieval of user and customer data associated with the connector. ### Method GET ### Endpoint /v1/connectors/{connector_id_or_name} ### Parameters #### Path Parameters - **connector_id_or_name** (string) - Required - The ID or name of the connector to retrieve. #### Query Parameters - **fetch_user_data** (boolean) - Optional - Fetch the user-level data associated with the connector (e.g. connection credentials). - **fetch_customer_data** (boolean) - Optional - Fetch the customer data associated with the connector (e.g. customer secrets / config). #### Request Body None ### Request Example ```python from mistralai.client import Mistral import os with Mistral( api_key=os.getenv("MISTRAL_API_KEY", ""), ) as mistral: res = mistral.beta.connectors.get(connector_id_or_name="", fetch_user_data=False, fetch_customer_data=False) # Handle response print(res) ``` ### Response #### Success Response (200) **models.Connector** - Represents the connector object with its associated data. #### Response Example ```json { "example": "response body" } ``` ### Errors - **errors.HTTPValidationError** - Status Code: 422 - Content Type: application/json - **errors.SDKError** - Status Code: 4XX, 5XX - Content Type: */* ``` -------------------------------- ### GET /v1/workflows/runs Source: https://github.com/mistralai/client-python/blob/main/docs/models/listrunsv1workflowsrunsgetresponse.md Retrieves a list of workflow executions. ```APIDOC ## GET /v1/workflows/runs ### Description Retrieves a list of workflow executions. ### Method GET ### Endpoint /v1/workflows/runs ### Response #### Success Response (200) - **result** (models.WorkflowExecutionListResponse) - The list of workflow executions. ``` -------------------------------- ### Initialize AudioContent model Source: https://github.com/mistralai/client-python/blob/main/docs/models/connectortoolcallresponsecontent.md Use this model to represent audio-based content in a tool call response. ```python value: models.AudioContent = /* values here */ ``` -------------------------------- ### GET /v1/conversations Source: https://github.com/mistralai/client-python/blob/main/docs/models/agentsapiv1conversationsgetrequest.md Retrieves metadata for a specific conversation. ```APIDOC ## GET /v1/conversations ### Description Retrieves metadata for a specific conversation using its ID. ### Method GET ### Endpoint /v1/conversations ### Parameters #### Query Parameters - **conversation_id** (str) - Required - ID of the conversation from which we are fetching metadata. ``` -------------------------------- ### Install Mistral AI SDK with Poetry Source: https://github.com/mistralai/client-python/blob/main/README.md Use this command to add the mistralai package to your project when using the Poetry dependency manager. ```bash poetry add mistralai ``` -------------------------------- ### CustomTaskStartedAttributesResponse Source: https://github.com/mistralai/client-python/blob/main/docs/models/customtaskstartedattributesresponse.md Represents the attributes of a custom task when it starts. ```APIDOC ## CustomTaskStartedAttributesResponse Attributes for custom task started events. ### Fields - **custom_task_id** (str) - Required - Unique identifier for the custom task within the workflow. - **custom_task_type** (str) - Required - The type/category of the custom task (e.g., 'llm_call', 'api_request'). - **payload** (Optional[models.JSONPayloadResponse]) - Optional - A payload containing arbitrary JSON data. Used for complete state snapshots or final results. When encrypted, the value field contains base64-encoded encrypted data and encoding_options indicates the type of encryption applied. ``` -------------------------------- ### Stream Agent Completions Source: https://github.com/mistralai/client-python/blob/main/docs/sdks/agents/README.md This example demonstrates how to stream responses from the Mistral AI agents API. It shows how to initialize the client, make a streaming request, and process the incoming events. ```APIDOC ## POST /v1/agents/completions#stream ### Description Allows streaming responses from an agent, providing partial results as they become available. The stream is terminated with a `data: [DONE]` message. Otherwise, the server holds the request open until timeout or completion, returning the full result as JSON. ### Method POST ### Endpoint /v1/agents/completions#stream ### Parameters #### Request Body - **messages** (list[dict]) - Required - A list of message objects representing the conversation history. - **agent_id** (str) - Required - The ID of the agent to interact with. - **stream** (bool) - Optional - If true, enables streaming of responses. Defaults to false. - **response_format** (dict) - Optional - Specifies the desired response format, e.g., `{"type": "text"}`. ### Request Example ```python from mistralai.client import Mistral import os with Mistral( api_key=os.getenv("MISTRAL_API_KEY", ""), ) as mistral: res = mistral.agents.stream(messages=[ { "role": "user", "content": "Who is the best French painter? Answer in one short sentence.", }, ], agent_id="", stream=True, response_format={ "type": "text", }) with res as event_stream: for event in event_stream: # handle event print(event, flush=True) ``` ### Response #### Success Response (200) - **event** (str) - Represents a chunk of the streamed response or a control message. #### Response Example ``` data: {"message": "..."} data: {"message": "..."} data: [DONE] ``` ``` -------------------------------- ### Initialize ResponseStartedEvent Source: https://github.com/mistralai/client-python/blob/main/docs/models/conversationeventsdata.md Represents the start of a response generation. ```python value: models.ResponseStartedEvent = /* values here */ ``` -------------------------------- ### Initialize WandbIntegration model Source: https://github.com/mistralai/client-python/blob/main/docs/models/createfinetuningjobrequestintegration.md Use this structure to define a Weights & Biases integration for fine-tuning jobs. ```python value: models.WandbIntegration = /* values here */ ``` -------------------------------- ### Using ShareEnum Source: https://github.com/mistralai/client-python/blob/main/docs/models/shareenum.md Demonstrates how to import and use the ShareEnum. Unrecognized values are handled as 'UnrecognizedStr'. ```python from mistralai.client.models import ShareEnum # Open enum: unrecognized values are captured as UnrecognizedStr value: ShareEnum = "Viewer" ``` -------------------------------- ### models.BuiltInConnectors Type Source: https://github.com/mistralai/client-python/blob/main/packages/azure/docs/models/toolreferencechunktool.md Example of assigning a value to the models.BuiltInConnectors type. ```python value: models.BuiltInConnectors = /* values here */ ``` -------------------------------- ### IndexMetricsOffline Model Source: https://github.com/mistralai/client-python/blob/main/docs/models/metricsdata.md Example of how to declare a variable of type models.IndexMetricsOffline. ```python value: models.IndexMetricsOffline = /* values here */ ``` -------------------------------- ### Initialize Mistral Client with Custom Async HTTP Client Source: https://github.com/mistralai/client-python/blob/main/README-PYPI.md Wrap an `httpx.AsyncClient` with a custom class implementing `AsyncHttpClient` to add logic like custom headers to all requests. ```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())) ``` -------------------------------- ### IndexMetricsOnline Model Source: https://github.com/mistralai/client-python/blob/main/docs/models/metricsdata.md Example of how to declare a variable of type models.IndexMetricsOnline. ```python value: models.IndexMetricsOnline = /* values here */ ``` -------------------------------- ### POST /v1/observability/datasets/{dataset_id}/imports/from-file Source: https://github.com/mistralai/client-python/blob/main/docs/sdks/datasets/README.md Populate a dataset with samples from an uploaded file. ```APIDOC ## POST /v1/observability/datasets/{dataset_id}/imports/from-file ### Description Populate the dataset with samples from an uploaded file. ### Method POST ### Endpoint /v1/observability/datasets/{dataset_id}/imports/from-file ### Parameters #### Path Parameters - **dataset_id** (str) - Required - N/A #### Request Body - **file_id** (str) - Required - N/A - **retries** (Optional[utils.RetryConfig]) - Optional - Configuration to override the default retry behavior of the client. ### Request Example ```python from mistralai.client import Mistral import os with Mistral( api_key=os.getenv("MISTRAL_API_KEY", ""), ) as mistral: res = mistral.beta.observability.datasets.import_from_file(dataset_id="1c96c925-cc58-4529-863d-9fe66a6f1924", file_id="") # Handle response print(res) ``` ### Response #### Success Response (200) - **models.DatasetImportTask** - Description of the task for importing the dataset. #### Response Example { "example": "response body" } ### Errors - **errors.ObservabilityError** - Status Code: 400, 404, 408, 409, 422, Content Type: application/json - **errors.SDKError** - Status Code: 4XX, 5XX, Content Type: */* ``` -------------------------------- ### Initialize MistralGCP Client with Custom httpx.Client Source: https://github.com/mistralai/client-python/blob/main/packages/gcp/README-PYPI.md Configure the MistralGCP client to use a custom httpx.Client instance with specific headers for all outgoing requests. ```python import os from mistralai.gcp.client import MistralGCP import httpx http_client = httpx.Client(headers={"x-custom-header": "someValue"}) s = MistralGCP( project_id=os.environ.get("GCP_PROJECT_ID"), region="us-central1", client=http_client, ) ``` -------------------------------- ### ChatCompletionChoiceFinishReason Usage Source: https://github.com/mistralai/client-python/blob/main/docs/models/chatcompletionchoicefinishreason.md Example of how to import and use the ChatCompletionChoiceFinishReason enum. ```APIDOC ## ChatCompletionChoiceFinishReason Enum ### Description This enum represents the reason why a chat completion sequence was stopped. It's an open enum, meaning that unrecognized values will not cause type errors and will be captured as `UnrecognizedStr`. ### Values - `"stop"`: Indicates that the model stopped generating text because it reached a natural stopping point. - `"length"`: Indicates that the model stopped generating text because it reached the maximum number of tokens allowed. - `"model_length"`: Indicates that the model stopped generating text because it reached the model's maximum length. - `"error"`: Indicates that an error occurred during generation. - `"tool_calls"`: Indicates that the model stopped generating text to make tool calls. ### Example Usage ```python from mistralai.client.models import ChatCompletionChoiceFinishReason # Assigning a valid enum value value: ChatCompletionChoiceFinishReason = "stop" # Assigning an unrecognized value (will be captured as UnrecognizedStr) # unrecognized_value: ChatCompletionChoiceFinishReason = "custom_reason" ``` ### Request Body Example This enum is typically used within the response of a chat completion API call, not directly in a request body. However, if you were to represent it in a request body, it would look like this: ```json { "finish_reason": "stop" } ``` ### Response Example When receiving a response from a chat completion API, the `finish_reason` field would be one of the enum values: ```json { "choices": [ { "message": { "role": "assistant", "content": "Hello! How can I help you today?" }, "finish_reason": "stop" } ] } ``` ``` -------------------------------- ### Create Agents Completions (Asynchronous) Source: https://github.com/mistralai/client-python/blob/main/README.md Make asynchronous agent completion requests with this example. It requires asyncio and the MISTRAL_API_KEY environment variable. Remember to set your agent_id. ```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()) ``` -------------------------------- ### Beta Agents Get Source: https://github.com/mistralai/client-python/blob/main/README.md Retrieves a specific agent entity. ```APIDOC ## Beta.Agents.get ### Description Retrieve an agent entity retrieves the details of a specific agent. ### Method Not specified (assumed to be a client SDK method call) ### Endpoint Not specified ### Parameters Not specified ### Request Example Not specified ### Response Not specified ``` -------------------------------- ### List Agents - Python Source: https://github.com/mistralai/client-python/blob/main/docs/sdks/betaagents/README.md Use this snippet to list available agents. It initializes the Mistral client with an API key and calls the agents.list method with pagination parameters. ```python from mistralai.client import Mistral import os with Mistral( api_key=os.getenv("MISTRAL_API_KEY", ""), ) as mistral: res = mistral.beta.agents.list(page=0, page_size=20) # Handle response print(res) ``` -------------------------------- ### Audio Voices Get Source: https://github.com/mistralai/client-python/blob/main/README.md Retrieves details for a specific voice. ```APIDOC ## Audio.Voices.get ### Description Get voice details for a specific voice. ### Method Not specified (assumed to be a client SDK method call) ### Endpoint Not specified ### Parameters Not specified ### Request Example Not specified ### Response Not specified ``` -------------------------------- ### Using ClassifierFineTuningJobDetailsStatus Source: https://github.com/mistralai/client-python/blob/main/docs/models/classifierfinetuningjobdetailsstatus.md Demonstrates how to import and use ClassifierFineTuningJobDetailsStatus. Unrecognized values are captured as UnrecognizedStr. ```python from mistralai.client.models import ClassifierFineTuningJobDetailsStatus # Open enum: unrecognized values are captured as UnrecognizedStr value: ClassifierFineTuningJobDetailsStatus = "QUEUED" ```