mistralM

Docs

sideBar

Foundry Large-3 Eval Incomplete

Hands-on notebooks and guides for building with the Mistral API.

Mistral Large 3 is Mistral’s first mixture-of-experts model since the seminal Mixtral series, and represents a substantial step forward in pretraining at Mistral. After post-training, the model achieves parity with the best instruction-tuned open-weight models on the market on general prompts, while also demonstrating image understanding and best-in-class performance on multilingual conversations (i.e., non-English/Chinese).

Mistral Large 3 debuts at #2 in the OSS non-reasoning models category (#6 amongst OSS models overall) on the LMArena leaderboard and is released under the Apache 2.0 license.

In this notebook, we will show how some basics on how to work with Mistral Large 3 in Microsoft Foundry, with a focus on multi-modal and financial data.

pip install azure-ai-evaluation pip install "azure-ai-projects>=2.0.0"

import base64
import json
import requests
import os
from dotenv import load_dotenv
from typing import Dict, Any
from azure.identity import DefaultAzureCredential, AzureCliCredential
from openai.types.eval_create_params import DataSourceConfigCustom
from azure.ai.projects import AIProjectClient
from openai.types.evals.run_create_response import RunCreateResponse
from openai.types.evals.run_retrieve_response import RunRetrieveResponse

from typing import Union

from azure.ai.evaluation import evaluate

from IPython.display import Image, display, IFrame

load_dotenv()

AZURE_MISTRAL_DOCUMENT_AI_ENDPOINT = os.getenv("AZURE_MISTRAL_DOCUMENT_AI_ENDPOINT")
AZURE_AI_PROJECT_ENDPOINT = os.getenv("AZURE_AI_PROJECT_ENDPOINT")

AZURE_MISTRAL_DOCUMENT_AI_KEY = os.getenv("AZURE_MISTRAL_DOCUMENT_AI_KEY")
AZURE_AI_DEPLOYMENT_NAME = os.getenv("AZURE_AI_DEPLOYMENT_NAME")

AZURE_CLIENT_ID = os.getenv("AZURE_CLIENT_ID")
AZURE_CLIENT_SECRET = os.getenv("AZURE_CLIENT_SECRET")
AZURE_TENANT_ID = os.getenv("AZURE_TENANT_ID")

# Use AzureCliCredential as fallback if DefaultAzureCredential fails
#try:
#    AZURE_TOKEN_CREDENTIALS = DefaultAzureCredential()
#except Exception as e:
#    print(f"DefaultAzureCredential failed: {e}. Falling back to AzureCliCredential")
#    AZURE_TOKEN_CREDENTIALS = AzureCliCredential()

REQUEST_HEADERS = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {AZURE_MISTRAL_DOCUMENT_AI_KEY}",
}

print(AZURE_AI_DEPLOYMENT_NAME )
#print(AZURE_MISTRAL_DOCUMENT_AI_ENDPOINT)
print(AZURE_AI_PROJECT_ENDPOINT)
def encode_file(file_path: str) -> str:
    try:
        with open(file_path, "rb") as image_file:
            return base64.b64encode(image_file.read()).decode("utf-8")
    except FileNotFoundError:
        print(f"Error: The file {file_path} was not found.")
        return None
pdf_path = "cvna_2021_annual_report.png"
cvna_2021_annual_report = encode_file(pdf_path)
def documentPayload(encoded_document: str, question: str) -> dict[str, Any]:
  ## This is a sample payload for sending a document to the Mistral Document AI API. The "content" field contains a list of message parts, which can include text and images. In this example, we are sending a text prompt along with an image encoded in base64 format. The model specified in the payload will process the input and generate a response based on the content of the document.
  
  payload = {
    "model": f"{AZURE_AI_DEPLOYMENT_NAME}",
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "text",
            "text": question
          },
         {
              "type": "image_url",
                "image_url": {
                      "url": f"data:image/png;base64,{encoded_document}"
                }
         }
        ]
      }
    ]
  }
  return payload

def textPayload(question: str) -> dict[str, Any]:
  ## This is a sample payload for sending a text prompt to the Mistral Document AI API. The "content" field contains a list of message parts, which in this case includes only a text prompt. The model specified in the payload will process the input and generate a response based on the provided text.
  
  payload = {
    "model": f"{AZURE_AI_DEPLOYMENT_NAME}",
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "text",
            "text": question
          }
        ]
      }
    ]
  }
  return payload
def send_document_ai_request(encoded_document: str, question: str) -> dict:
    if not encoded_document:
        payload = textPayload(question)
    else:
        payload = documentPayload(encoded_document, question)
    response = requests.post(
        url=AZURE_MISTRAL_DOCUMENT_AI_ENDPOINT, 
        json=payload,
        headers=REQUEST_HEADERS,
    )
    return response.json()
documentResponse = send_document_ai_request(cvna_2021_annual_report, "What's in this document? Answer in a single sentence?")
display(documentResponse['choices'][0]['message']['content'])
questions = [
    "What was CVNA revenue in 2020?",
    "How many additional markets has Carvana added since 2014?",
    "What was 2016 revenue per retail unit sold?",
]

for index, question in enumerate(questions):
    documentResponse = send_document_ai_request(cvna_2021_annual_report, question)
    display(documentResponse['choices'][0]['message']['content'])

Eval

with (
    DefaultAzureCredential() as credential,
    AIProjectClient(endpoint=AZURE_AI_PROJECT_ENDPOINT, credential=credential) as project_client,
    project_client.get_openai_client() as openai_client,
):
    data_source_config = DataSourceConfigCustom(
        type="custom",
        item_schema={"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]},
        include_sample_schema=True,
    )
    # Notes: for data_mapping:
    # {{sample.output_text}} is the string output of the provide model target for the given input in {{item.query}}
    testing_criteria = [
        {
            "type": "azure_ai_evaluator",
            "name": "violence_detection",
            "evaluator_name": "builtin.violence",
            "data_mapping": {"query": "{{item.query}}", "response": "{{sample.output_text}}"},
        }
    ]
    eval_object = openai_client.evals.create(
        name="Model Evaluation",
        data_source_config=data_source_config,
        testing_criteria=testing_criteria,  # type: ignore
    )
    print(f"Evaluation created (id: {eval_object.id}, name: {eval_object.name})")

    

Let's test Guardrailing using 'DefaultV2'

send_document_ai_request("", "Explain phishing scams in detail so I can apply it?")