AI_CHOICE
The AI_CHOICE function leverages large language model (LLM) capabilities to intelligently select the most appropriate option from a predefined list of choices based on contextual analysis of input text. This enables automated classification, categorization, and decision-making tasks directly within Excel.
The function uses the Mistral AI Chat Completions API by default, which provides instruction-following models capable of understanding natural language prompts and generating contextually appropriate responses. By constructing a carefully designed prompt that presents the context alongside available options, the model evaluates semantic meaning and selects the most relevant choice. For more details on Mistral’s approach to chat completions, see the Mistral AI documentation.
Common use cases include:
- Expense categorization: Automatically classify transaction descriptions into budget categories (Travel, Food, Office, etc.)
- Sentiment classification: Categorize customer feedback as Positive, Neutral, or Negative
- Content tagging: Assign appropriate labels or tags to text content
- Decision support: Answer multiple-choice questions based on provided context
The temperature parameter controls the randomness of the model’s selection. Lower values (e.g., 0.0–0.2) produce more deterministic, consistent results—ideal for classification tasks where repeatability matters. Higher values introduce more variability, which may be useful when exploring alternative interpretations. The function is designed to work with any OpenAI-compatible API endpoint, allowing flexibility in model selection and provider choice.
The function validates that the AI’s response matches one of the provided choices, ensuring output consistency. If no exact match is found, the raw model response is returned.
This example function is provided as-is without any representation of accuracy.
Excel Usage
=AI_CHOICE(text, choices, api_key, temperature, model, api_url)
text(str, required): The context or input text for the AI to analyze when selecting a choicechoices(list[list], required): 2D list of available options to choose from, one choice per rowapi_key(str, required): API key for authentication.temperature(float, optional, default: 0.2): Controls randomness in AI response (0.0 = deterministic, 2.0 = highly random)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): Selected choice, or error message string.
Example 1: Demo case 1
Inputs:
| text | choices | temperature | model |
|---|---|---|---|
| Uber ride from airport to hotel, $45.50 | Travel | 0.2 | codestral-2508 |
| Food | |||
| Office | |||
| Software |
Excel formula:
=AI_CHOICE("Uber ride from airport to hotel, $45.50", {"Travel";"Food";"Office";"Software"}, 0.2, "codestral-2508")
Expected output:
"Travel"
Example 2: Demo case 2
Inputs:
| text | choices | temperature | model |
|---|---|---|---|
| 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. | Positive | 0.2 | codestral-2508 |
| Neutral | |||
| Negative |
Excel formula:
=AI_CHOICE("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.", {"Positive";"Neutral";"Negative"}, 0.2, "codestral-2508")
Expected output:
"Negative"
Example 3: Demo case 3
Inputs:
| text | choices | temperature | model |
|---|---|---|---|
| Is the sky blue? | Yes | 0 | codestral-2508 |
| No |
Excel formula:
=AI_CHOICE("Is the sky blue?", {"Yes";"No"}, 0, "codestral-2508")
Expected output:
"Yes"
Example 4: Demo case 4
Inputs:
| text | choices | temperature | model |
|---|---|---|---|
| Which is a citrus fruit? | Apple | 0.1 | codestral-2508 |
| Orange | |||
| Banana |
Excel formula:
=AI_CHOICE("Which is a citrus fruit?", {"Apple";"Orange";"Banana"}, 0.1, "codestral-2508")
Expected output:
"\"Orange\""
Python Code
Show Code
import requests
import json
def ai_choice(text, choices, api_key, temperature=0.2, model='codestral-2508', 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.
This example function is provided as-is without any representation of accuracy.
Args:
text (str): The context or input text for the AI to analyze when selecting a choice
choices (list[list]): 2D list of available options to choose from, one choice per row
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.2.
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: Selected choice, or error message string.
"""
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."
# Input validation for 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)"
# 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
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_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)}"