AI_CHOICE
Overview
This function uses AI to classify or select the most appropriate option from a list of choices based on provided text. It’s ideal for categorization tasks, sentiment analysis, prioritization, and other decision-making processes where multiple options need to be evaluated against a text description.
Usage
Analyzes a text description and selects the most suitable option from the provided choices.
=AI_CHOICE(text, choices, [temperature], [model], [api_key], [api_url])
Parameters
Parameter | Type | Required | Description |
---|---|---|---|
text | string/2D list | Yes | The text to classify or analyze. |
choices | string/2D list | Yes | The options to choose from (comma-separated string or range with one option per cell). |
temperature | float | No | Controls the randomness/creativity of the response (0.0 to 2.0). Higher values mean more creative. |
model | string | No | The specific AI model ID to use for the request (e.g., ‘mistral-small’, ‘mistral-large’). |
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 which supports CORS . |
Returns:
Return Value | Type | Description |
---|---|---|
Result | string | The selected choice from the provided options |
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 result depends on the clarity of the text and the options provided.
- Large lists or long text 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.- If you hit the API rate limit for your provider, a message is returned instead of raising an exception.
Benefits
- Automates classification, prioritization, and decision-making directly in Excel.
- Saves time and improves consistency in business processes.
- Enables dynamic, context-aware choices using your own data.
- More flexible and powerful than manual or native Excel approaches for classification and selection.
Examples
1. Finance: Expense Categorization
Categorize an expense transaction based on its description.
Input Text (Cell A1
):
Uber ride from airport to hotel, $45.50
Choices (Range B1:B4
):
Travel
Food
Office
Software
=AI_CHOICE(A1, B1:B4)
Sample Output: “Travel”
2. Customer Service: Email Sentiment Analysis
Classify the sentiment of a customer email to prioritize responses.
Input Text (Cell A1
):
I've been waiting for a response about my refund for over two weeks now. This is completely unacceptable and I'm considering filing a complaint.
Choices (Range B1:B3
):
Positive
Neutral
Negative
=AI_CHOICE(A1, B1:B3)
Sample Output: “Negative”
3. Sales: Lead Qualification
Determine the qualification level of a sales lead based on interaction notes.
Input Text (Cell A1
):
Company: Acme Corp (250+ employees). Contact expressed interest in enterprise plan, requested pricing information, and scheduled a demo next week. Budget confirmed. Decision timeline: end of quarter.
Choices (Range B1:B3
):
Hot Lead
Warm Lead
Cold Lead
=AI_CHOICE(A1, B1:B3)
Sample Output: “Hot Lead”
4. IT Support: Ticket Prioritization
Assign a priority level to a support ticket based on its description.
Input Text (Cell A1
):
Unable to access CRM system. Getting error 500 when trying to load customer records. This is affecting sales team productivity but they can still use other systems in the meantime.
Choices (Range B1:B4
):
Critical Priority
High Priority
Medium Priority
Low Priority
=AI_CHOICE(A1, B1:B4)
Sample Output: “High Priority”
5. Product Management: Feedback Categorization
Categorize customer feedback into actionable feedback types.
Input Text (Cell A1
):
I love the new dashboard layout, but it would be even better if I could customize which widgets appear and their positions on the screen.
Choices (Range B1:B5
):
Bug Report
Feature Request
UI Feedback
Performance Issue
Compliment
=AI_CHOICE(A1, B1:B5)
Sample Output: “Feature Request”
6. Legal: Document Classification
Classify a legal document based on its content.
Input Text (Cell A1
):
This agreement outlines the terms under which Company A will provide consulting services to Company B, including scope of work, deliverables, timeline, and compensation structure.
Choices (Single Cell with Commas, Cell B1
):
NDA, Service Agreement, Employment Contract, License Agreement
=AI_CHOICE(A1, B1)
Sample Output: “Service Agreement”
Source Code
import requests
import json
# This function uses AI to select the most appropriate choice from a list of options based on the given context.
def ai_choice(text, choices, temperature=0.2, model='mistral-small-latest', api_key=None, api_url="https://api.mistral.ai/v1/chat/completions"):
"""
Uses AI to select the most appropriate choice from a list of options based on the given context.
Args:
text (str or 2D list): The context, question, or scenario used for decision-making
choices (str or 2D list): A string with comma-separated options or a 2D list of options
temperature (float, optional): Controls randomness in the selection (0-2). Default is 0.2
model (str, optional): ID of the AI 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 selected choice from the options provided
"""
# Demo login fallback
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.")
# Input validation for 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)")
# Normalize text to string if it's a 2D list
if isinstance(text, list):
text_str = "\n".join([item[0] if isinstance(item, list) and len(item) > 0 else str(item) for item in text if len(item) > 0])
else:
text_str = text
# Normalize choices to a list of strings
if isinstance(choices, list):
choices_list = [item[0] if isinstance(item, list) and len(item) > 0 else str(item) for item in choices]
else:
choices_list = [choice.strip() for choice in str(choices).split(',') if choice.strip()]
if not text_str or text_str.strip() == "":
return "Error: Empty input text."
if not choices_list or all([c.strip() == "" for c in choices_list]):
return "Error: No valid choices provided."
# Construct the AI prompt
prompt = f"""Based on the following context, select the single most appropriate option from the choices provided.\n\nContext:\n{text_str}\n\nChoices:\n{json.dumps(choices_list, indent=2)}\n\nProvide ONLY your selected choice without explanation or additional text. Return the exact text of the selected choice."""
# Prepare the API request payload
payload = {
"messages": [{"role": "user", "content": prompt}],
"temperature": temperature,
"model": model,
"max_tokens": 200
}
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"Accept": "application/json"
}
# Make the API request
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."
try:
# Extract and return the response content
response_data = response.json()
content = response_data["choices"][0]["message"]["content"].strip()
# Validate that the response is one of the choices
for choice in choices_list:
if choice == content:
return choice
# If no exact match, return the AI's response (which may be a paraphrase)
return content
except Exception as e:
return f"Error: Failed to get AI recommendation. {str(e)}"