AI_FORMAT
Overview
This function uses an AI model to standardize and restructure text based on a specified format. It is especially useful for cleaning and organizing inconsistent data in a structured way, making it easier to work with data from various sources.
Usage
To use the AI_FORMAT
function in Excel, enter it as a formula in a cell, specifying your text, format instruction, and any optional arguments as needed:
=AI_FORMAT(text, format_instruction, [temperature], [max_tokens], [model], [api_key], [api_url])
Replace each parameter with your desired value. The function returns the formatted text generated by the AI model.
Parameters
Parameter | Type | Required | Description |
---|---|---|---|
text | string/range | Yes | The text or cell reference containing the data to format. |
format_instruction | string | Yes | The desired output format description (e.g., “ISO date format”, “formal business letter”). |
temperature | float | No | Controls the randomness/creativity of the response (0.0 to 2.0). Lower values are more deterministic. |
max_tokens | int | No | Maximum number of tokens for the generated formatted content (5 to 5000). |
model | string | No | The specific AI model ID to use (e.g., ‘mistral-small-latest’). |
api_key | string | No | API key for authentication. Get a free API key from Mistral AI . |
api_url | string | No | OpenAI-compatible API endpoint URL (e.g., https://api.mistral.ai/v1/chat/completions ). |
Return Value
Return Value | Type | Description |
---|---|---|
Formatted Text | string | The reformatted text according to the specified format. Returns an error message on failure. |
Demo
If either api_key
or api_url
is not provided, both will default to Boardflare demo values (api_url
: https://llm.boardflare.com , api_key
: your Microsoft login token if available). This only works for users logged in with a Microsoft account and provides limited free demo usage. You may obtain a free api_key for Mistral AI with your Microsoft account which offers more generous free usage and supports CORS.
Limitations
- The quality of the output depends on the clarity of the format instruction and the input text.
- Large text inputs may exceed model context limits and result in truncated or incomplete responses.
- The function requires an internet connection to access the AI model.
- Model availability and output may vary depending on the provider or API changes.
- Sensitive or confidential data should not be sent to external AI services.
temperature
must be a float between 0 and 2 (inclusive). If not, a ValueError is raised.max_tokens
must be an integer between 5 and 5000 (inclusive). If not, a ValueError is raised.- If you hit the API rate limit for your provider, a message is returned instead of raising an exception.
Benefits
- Automates text formatting, standardization, and business writing directly in Excel.
- Saves time and improves consistency in reporting and communication.
- Enables dynamic, context-aware formatting using your own data.
- More flexible and powerful than manual or native Excel approaches for text formatting and standardization.
Examples
Standardizing Customer Contact Information
Format inconsistent customer data into a standard format.
Sample Input:
=AI_FORMAT("John Smith / Marketing Director - Acme Inc / [email protected] - 555.123.4567", "standard business contact card format")
Sample Output:
John Smith
Marketing Director
Acme Inc.
Email: [email protected]
Phone: (555) 123-4567
Formatting Financial Figures
Standardize financial figures for reporting.
Sample Input:
=AI_FORMAT("Revenue: 2.4m; COGS: 1.1m; Gross Margin: 1.3m (54%); Opex: 950k; EBITDA: 350k", "professional financial statement format with proper currency notation")
Sample Output:
Revenue: 1,100,000
Gross Margin: 950,000
EBITDA: $350,000
Converting Customer Feedback to Structured Format
Format free-form customer feedback into a structured review.
Sample Input:
=AI_FORMAT("Used the product for 3 weeks. Good quality but shipping took forever. Customer service was helpful though. Probably would buy again if they fix delivery issues.", "structured product review with ratings")
Sample Output:
Overall Rating: 3.5/5
Product Quality: 4/5 - Good quality product
Shipping & Delivery: 2/5 - Excessive delivery time
Customer Service: 4/5 - Helpful support
Would Purchase Again: Yes, conditionally
Additional Comments: Customer would likely repurchase if delivery issues are resolved.
Standardizing Address Data
Format inconsistent address entries into a standard format.
Sample Input:
=AI_FORMAT("123 business park dr suite 12, austin tx 78701", "standard US business address format")
Sample Output:
123 Business Park Drive
Suite 12
Austin, TX 78701
Converting Notes to Action Item Format
Format meeting notes into a structured action item list.
Sample Input:
=AI_FORMAT("Tom said we need to finish the report by Friday. Maria will contact the client about budget concerns. Everyone should review the new marketing strategy before next meeting on 5/10.", "action items with responsible parties and deadlines")
Sample Output:
ACTION ITEMS:
1. [Tom] Complete report - Due: Friday
2. [Maria] Contact client regarding budget concerns - Due: ASAP
3. [All Team Members] Review new marketing strategy - Due: Before May 10 meeting
Source Code
import requests
import json
def ai_format(text, format_instruction, temperature=0.0, max_tokens=1500, model='mistral-small-latest', api_key=None, api_url="https://api.mistral.ai/v1/chat/completions"):
"""
Uses AI to format text according to a specific structure or pattern.
Args:
text (str or list): The text to format (string or 2D list with a single cell)
format_instruction (str): Instructions describing the desired format
temperature (float, optional): Controls response creativity (0-2). Default is 0.0
max_tokens (int, optional): Maximum tokens for response generation. Default is 1500
model (str, optional): ID of the model to use
api_key (str, optional): API key for authentication (e.g. for Mistral AI)
api_url (str, optional): OpenAI compatible URL. (e.g., https://api.mistral.ai/v1/chat/completions for Mistral AI)
Returns:
str: The formatted text according to the specified format
"""
# Demo fallback: Boardflare endpoint if no api_key or api_url
if api_key is None or api_url is None:
if 'idToken' in globals():
api_key = globals()['idToken']
api_url = "https://llm.boardflare.com"
else:
return ("Login on the Functions tab for limited demo usage, or sign up for a free Mistral AI account at https://console.mistral.ai/ and add your own api_key.")
# 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):
raise ValueError("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):
raise ValueError("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": temperature,
"model": model,
"max_tokens": max_tokens
}
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"Accept": "application/json"
}
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()