AI_FORMAT

The AI_FORMAT function uses a large language model (LLM) to transform text according to specified formatting instructions. By leveraging the Mistral AI Chat Completions API, this function automates text transformation tasks such as case conversion, restructuring, data format conversion, and pattern-based text rewriting—going beyond simple string operations to handle context-aware transformations.

The function accepts input text and a format instruction (e.g., “convert to title case”, “format as JSON”, “create bullet points”) and sends both to an LLM for processing. The model interprets the semantic intent of the formatting request and returns the appropriately transformed text. This approach differs from traditional string functions because it understands natural language instructions and can handle complex, context-dependent formatting rules that would be difficult to express programmatically.

Typical use cases include converting text to different cases (title, uppercase, lowercase, sentence case), reformatting lists or data into different structures (CSV to JSON, prose to bullet points, paragraphs to tables), standardizing naming conventions, creating summaries in specific formats, and transforming text to match required output specifications. The function is particularly valuable when formatting requirements are complex or when input text structure varies significantly.

By default, the function uses Mistral Small, a cost-effective model suitable for straightforward text formatting tasks. The api_url parameter accepts any OpenAI-compatible API endpoint, enabling integration with alternative LLM providers. The deterministic default (temperature=0) ensures consistent formatting across multiple invocations, making it reliable for batch processing and automated workflows. The max_tokens parameter (default 1500, range 5 to 5000) controls output length and API costs.

For more information about available models and API usage, see the Mistral AI documentation and the Mistral AI GitHub repository.

This example function is provided as-is without any representation of accuracy.

Excel Usage

=AI_FORMAT(text, format_instruction, api_key, temperature, max_tokens, model, api_url)
  • text (str, required): The text to format according to the instruction
  • format_instruction (str, required): Instructions describing the desired output format (e.g., “title case”, “JSON”)
  • api_key (str, required): API key for authentication.
  • temperature (float, optional, default: 0): Controls randomness in AI response (0.0 = deterministic, 2.0 = highly random)
  • max_tokens (int, optional, default: 1500): Maximum tokens in the AI response (5 to 5000)
  • model (str, optional, default: “codestral-2508”): Model ID to use. Default is “codestral-2508”.
  • api_url (str, optional, default: “https://api.mistral.ai/v1/chat/completions”): OpenAI-compatible API endpoint URL. Default is “https://api.mistral.ai/v1/chat/completions”.

Returns (str): The formatted text according to the specified format, or an error message on failure.

Example 1: Demo case 1

Inputs:

text format_instruction
hello world Format this text to title case.

Excel formula:

=AI_FORMAT("hello world", "Format this text to title case.")

Expected output:

"Hello World"

Example 2: Demo case 2

Inputs:

text format_instruction
hello world Format this text to uppercase.

Excel formula:

=AI_FORMAT("hello world", "Format this text to uppercase.")

Expected output:

"HELLO WORLD"

Example 3: Demo case 3

Inputs:

text format_instruction
HELLO WORLD Format this text to lowercase.

Excel formula:

=AI_FORMAT("HELLO WORLD", "Format this text to lowercase.")

Expected output:

"hello world"

Example 4: Demo case 4

Inputs:

text format_instruction
hello world Capitalize the first letter of the text.

Excel formula:

=AI_FORMAT("hello world", "Capitalize the first letter of the text.")

Expected output:

"Hello world"

Python Code

Show Code
import requests
import json

def ai_format(text, format_instruction, api_key, temperature=0, max_tokens=1500, model='codestral-2508', api_url='https://api.mistral.ai/v1/chat/completions'):
    """
    Uses an AI model to format text according to a specific structure or pattern.

    This example function is provided as-is without any representation of accuracy.

    Args:
        text (str): The text to format according to the instruction
        format_instruction (str): Instructions describing the desired output format (e.g., "title case", "JSON")
        api_key (str): API key for authentication.
        temperature (float, optional): Controls randomness in AI response (0.0 = deterministic, 2.0 = highly random) Default is 0.
        max_tokens (int, optional): Maximum tokens in the AI response (5 to 5000) Default is 1500.
        model (str, optional): Model ID to use. Default is "codestral-2508". Default is 'codestral-2508'.
        api_url (str, optional): OpenAI-compatible API endpoint URL. Default is "https://api.mistral.ai/v1/chat/completions". Default is 'https://api.mistral.ai/v1/chat/completions'.

    Returns:
        str: The formatted text according to the specified format, or an error message on failure.
    """
    if not api_key:
        return "You must include an API key to use this function. Sign up for a free API key at https://aistudio.google.com/, https://console.mistral.ai/, or other providers and add your own api_key.  You may use any OpenAI compatible API, just update the api_url parameter."

    # Handle 2D list input (flatten to a single string)
    if isinstance(text, list):
        if len(text) > 0 and len(text[0]) > 0:
            text = str(text[0][0])
        else:
            return "Error: Empty input text."

    # Validate temperature
    if not isinstance(temperature, (float, int)) or not (0 <= float(temperature) <= 2):
        return "Error: temperature must be a float between 0 and 2 (inclusive)."
    # Validate max_tokens
    if not isinstance(max_tokens, int) or not (5 <= max_tokens <= 5000):
        return "Error: max_tokens must be an integer between 5 and 5000 (inclusive)."

    # Construct a specific prompt for formatting
    format_prompt = f"Format the following text according to this format instruction: {format_instruction}\n\nText to format: {text}"
    format_prompt += "\n\nReturn ONLY the formatted text. Do not include any explanatory text, just the formatted text."

    # Prepare the API request payload
    payload = {
        "messages": [{"role": "user", "content": format_prompt}],
        "temperature": float(temperature),
        "model": model,
        "max_tokens": max_tokens
    }

    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
        "Accept": "application/json"
    }

    try:
        response = requests.post(api_url, headers=headers, json=payload)
        if response.status_code == 429:
            return "You have hit the rate limit for the API. Please try again later."
        response.raise_for_status()
        response_data = response.json()
        content = response_data["choices"][0]["message"]["content"]
        return content.strip()
    except Exception as e:
        return f"Error: {str(e)}"

Online Calculator

The text to format according to the instruction
Instructions describing the desired output format (e.g., "title case", "JSON")
API key for authentication.
Controls randomness in AI response (0.0 = deterministic, 2.0 = highly random)
Maximum tokens in the AI response (5 to 5000)
Model ID to use. Default is "codestral-2508".
OpenAI-compatible API endpoint URL. Default is "https://api.mistral.ai/v1/chat/completions".