Getting started overview

This guide provides the necessary steps to begin using the Mistral AI API, covering account setup, API key generation, and executing an initial request. Mistral AI offers a suite of models, including Mistral Large, Mistral Small, and Mistral Tiny, designed for various text generation and embedding tasks. The API is accessible via standard HTTP requests and is supported by a Mistral AI Python SDK.

The core interaction involves sending a request to a model endpoint with your input data and API key, then processing the JSON response. This process is consistent whether you are generating text, creating embeddings, or fine-tuning models.

Quick Reference Steps

The following table outlines the key steps to get started with Mistral AI:

Step What to Do Where
1. Sign Up Create a Mistral AI account. Mistral AI Console
2. Generate API Key Create a new API key from your account dashboard. API Keys section
3. Install SDK (Optional) Install the Python SDK or prepare a cURL environment. Terminal (pip install mistralai)
4. Make Request Send your first API call using cURL or Python. Code editor/terminal
5. Review Response Examine the API's JSON output for generated content or embeddings. Code editor/terminal

Create an account and get keys

Access to the Mistral AI API requires an account and an API key. This key authenticates your requests and links them to your usage for billing purposes. Mistral AI operates on a pay-as-you-go pricing model, with costs based on tokens consumed by input and output across different models.

Account Creation

  1. Navigate to the Mistral AI Console.
  2. Click on 'Sign Up' and follow the prompts to register. This typically involves providing an email address and creating a password.
  3. Verify your email address if prompted.

Generating an API Key

After creating and logging into your account, you can generate an API key:

  1. From the Mistral AI Console dashboard, locate the navigation menu and select 'API Keys' or similar. A direct link is available at Mistral AI API Keys page.
  2. Click the 'Create New Key' button.
  3. Provide a descriptive name for your API key (e.g., "My First App Key"). This helps in identifying its purpose later.
  4. The system will generate a unique key. Copy this key immediately, as it will only be shown once for security reasons. Store it securely; it will be used to authenticate all your API requests.

For best practices, avoid hardcoding API keys directly into your application code. Use environment variables or a secure configuration management system. For example, in a Python application, you might load the key using os.environ.get("MISTRAL_API_KEY").

Your first request

Once you have your API key, you can make your first request. This section demonstrates how to generate text using the Chat Completions endpoint, which is a common starting point for interacting with large language models. Examples are provided for both cURL and Python.

Prerequisites

  • Your Mistral AI API Key.
  • For Python: Python 3.8+ installed.
  • For cURL: cURL installed (usually pre-installed on Unix-like systems).

Using cURL

cURL is a command-line tool for making HTTP requests. This example sends a request to the chat completions endpoint using the mistral-tiny model.

curl -X POST \ 
  https://api.mistral.ai/v1/chat/completions \ 
  -H "Content-Type: application/json" \ 
  -H "Accept: application/json" \ 
  -H "Authorization: Bearer YOUR_API_KEY" \ 
  -d '{ 
    "model": "mistral-tiny", 
    "messages": [{"role": "user", "content": "What is the capital of France?"}] 
  }'

Replace YOUR_API_KEY with the API key you generated. The -d flag specifies the JSON payload, which includes the model to use and the user's message. The Accept: application/json header indicates that the client expects a JSON response, a common pattern for HTTP content negotiation.

A successful response will return a JSON object containing the model's reply:

{
  "id": "cmpl-xxxxxxxxxxxxxxxxxxxxxx",
  "object": "chat.completion",
  "created": 1700000000,
  "model": "mistral-tiny",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "The capital of France is Paris."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 10,
    "completion_tokens": 7,
    "total_tokens": 17
  }
}

Using Python SDK

The Mistral AI Python SDK simplifies interactions with the API. First, install the SDK:

pip install mistralai

Then, create a Python script (e.g., first_request.py) with the following content:

from mistralai.client import MistralClient
from mistralai.models.chat_completion import ChatMessage
import os

# Ensure your API key is loaded from an environment variable
api_key = os.environ.get("MISTRAL_API_KEY")

if not api_key:
    raise ValueError("MISTRAL_API_KEY environment variable not set.")

client = MistralClient(api_key=api_key)

messages = [
    ChatMessage(role="user", content="What is the capital of France?")
]

try:
    chat_response = client.chat(model="mistral-tiny", messages=messages)
    print(chat_response.choices[0].message.content)
except Exception as e:
    print(f"An error occurred: {e}")

Before running the script, set your API key as an environment variable:

Linux/macOS:

export MISTRAL_API_KEY="YOUR_API_KEY"

Windows (Command Prompt):

set MISTRAL_API_KEY="YOUR_API_KEY"

Windows (PowerShell):

$env:MISTRAL_API_KEY="YOUR_API_KEY"

Then, execute the Python script:

python first_request.py

The output should be similar to: The capital of France is Paris.

Common next steps

After successfully making your first request, consider these common next steps to further integrate and optimize your use of Mistral AI:

  • Explore Different Models: Experiment with Mistral AI's other models, such as mistral-small for more complex tasks or mistral-large for premium performance. Each model has different capabilities and pricing.
  • Generate Embeddings: Utilize the mistral-embed model to convert text into numerical vector representations. This is crucial for tasks like semantic search, recommendation systems, and clustering. Refer to the Mistral Embed API documentation.
  • Implement Streaming: For real-time applications or long-form content generation, implement streaming responses to receive tokens as they are generated, improving user experience.
  • Manage API Keys: For production environments, implement robust API key management. Rotate keys regularly and use environment variables or a secrets manager to keep them secure.
  • Error Handling: Implement comprehensive error handling in your applications to gracefully manage API rate limits, invalid requests, and other potential issues. The Mistral AI API documentation on error handling provides details on status codes and error messages.
  • Monitor Usage: Regularly check your usage in the Mistral AI Console to monitor token consumption and manage costs effectively.
  • Review Pricing: Understand the Mistral AI pricing structure for different models and token types (input vs. output) to optimize cost efficiency.

Troubleshooting the first call

Encountering issues during your first API call is common. Here are some troubleshooting tips:

  • Invalid API Key:
    • Symptom: HTTP 401 Unauthorized error or similar authentication failure.
    • Solution: Double-check that your API key is correct and has not expired. Ensure there are no leading or trailing spaces. Regenerate the key if necessary from the Mistral AI API Keys page.
  • Incorrect Endpoint or Model Name:
    • Symptom: HTTP 404 Not Found or HTTP 400 Bad Request.
    • Solution: Verify the API endpoint URL (e.g., https://api.mistral.ai/v1/chat/completions) and the model name (e.g., mistral-tiny) against the Mistral AI API reference. Model names are case-sensitive.
  • Malformed JSON Request Body:
    • Symptom: HTTP 400 Bad Request with a message indicating JSON parsing failure.
    • Solution: Ensure your JSON payload is correctly formatted. Check for missing commas, incorrect quotes, or mismatched brackets. Online JSON validators can help identify syntax errors.
  • Missing Headers:
    • Symptom: HTTP 400 Bad Request or unexpected behavior.
    • Solution: Confirm that you are sending the required headers: Content-Type: application/json and Authorization: Bearer YOUR_API_KEY.
  • Environment Variable Not Set (Python SDK):
    • Symptom: ValueError: MISTRAL_API_KEY environment variable not set.
    • Solution: Ensure you have correctly set the MISTRAL_API_KEY environment variable in your terminal before running the Python script. Remember that environment variables are session-specific.
  • Network Issues:
    • Symptom: Connection timeouts or inability to reach the API endpoint.
    • Solution: Check your internet connection. If using a corporate network, ensure no firewall rules are blocking access to api.mistral.ai. You can test connectivity with a simple ping api.mistral.ai command.
  • Rate Limiting:
    • Symptom: HTTP 429 Too Many Requests.
    • Solution: You've sent too many requests in a short period. Implement exponential backoff or wait before retrying. Refer to the Mistral AI error handling documentation for rate limit specifics.