mistralM

Docs

sideBar

Foundry Mistral Small Qna

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

Mistal Small 2503 'mistral-small-2503' for Question and Answer on pdf files: https://docs.mistral.ai/studio-api/document-processing/document_qna

import requests
import base64
import os
from dotenv import load_dotenv
from typing import Any
from pdf2image import convert_from_path


from IPython.display import Image, display  

load_dotenv()

AZURE_MISTRAL_MODEL_ENDPOINT = os.getenv("AZURE_MISTRAL_MODEL_ENDPOINT")
AZURE_MISTRAL_MODEL_KEY = os.getenv("AZURE_MISTRAL_MODEL_KEY")

AZURE_AI_QNA_MODEL= os.getenv("AZURE_AI_QNA_MODEL")

REQUEST_HEADERS = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {AZURE_MISTRAL_MODEL_KEY}",
}
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
def documentPayload(encoded_document: str, question: str, mime_type: str = "image/png") -> dict[str, Any]:
    payload = {
        "model": f"{AZURE_AI_QNA_MODEL}",
        "messages": [
        {
            "role": "user",
            "content": [
            {
                "type": "text",
                "text": question
            },
            {
                "type": "image_url",
                "image_url": {
                      "url": f"data:{mime_type};base64,{encoded_document}"
                }
            }
            ]
        }
        ]
    }
    return payload
def pdf_to_png(pdf_path: str, output_path: str = None, dpi: int = 200) -> str:
    """Convert first page of a PDF to PNG. Returns the output file path."""
    pages = convert_from_path(pdf_path, dpi=dpi)
    if not pages:
        raise ValueError(f"No pages found in {pdf_path}")
    if output_path is None:
        output_path = pdf_path.replace(".pdf", ".png")
    pages[0].save(output_path, "PNG")
    return output_path

png_path = pdf_to_png("wordpress-pdf-invoice-plugin-sample.pdf")
#print(f"Saved: {png_path}")
#display(Image(filename=png_path))

encoded_document = encode_file(png_path)
payload = documentPayload(encoded_document, "what is the last sentence in the document?")

response = requests.post(
        url=AZURE_MISTRAL_MODEL_ENDPOINT, 
        json=payload,
        headers=REQUEST_HEADERS,
    )

print(response.json())