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])
Arguments:
Argument | Type | Description | Default |
---|---|---|---|
text | string or range | The text to classify or analyze | |
choices | string or range | The options to choose from (either a comma-separated string or a range with one option per cell) | |
temperature | float | Optional: Controls the randomness in selection (0.0-1.0). Lower values for more deterministic results | 0.2 |
model | string | Optional: The specific AI model to use for the classification | mistral-small-latest |
Returns:
Return Value | Type | Description |
---|---|---|
Result | string | The selected choice from the provided options |
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
def ai_choice(text, choices, temperature=0.2, model='mistral-small-latest'):
"""
Uses AI to select the most appropriate choice from a list of options based on the given context.
Args:
text (str or list): The context, question, or scenario used for decision-making
choices (str or list): A string with comma-separated options or a 2D list of options
temperature (float, optional): Controls randomness in the selection (0-1). Default is 0.2
model (str, optional): ID of the AI model to use
Returns:
str: The selected choice from the options provided
"""
# Input validation
if not text or (isinstance(text, list) and (len(text) == 0 or len(text[0]) == 0)):
return "Error: Empty input text."
if not choices or (isinstance(choices, list) and (len(choices) == 0 or len(choices[0]) == 0)):
return "Error: No valid choices provided."
# Normalize text to string if it's a 2D list
if isinstance(text, list):
text_str = "\n".join([item[0] if isinstance(item[0], str) else str(item[0]) 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(',')]
# Construct the AI prompt
prompt = f"""Based on the following context, select the single most appropriate option from the choices provided.
Context:
{text_str}
Choices:
{json.dumps(choices_list, indent=2)}
Provide ONLY your selected choice without explanation or additional text. Return the exact text of the selected choice."""
# Using Boardflare API for demo purposes. Replace with any OpenAI compatible API endpoint.
# Sign up for your free Mistral API account at https://console.mistral.ai/ then replace the following:
api_url = "https://llm.boardflare.com" # replace with "https://api.mistral.ai/v1/chat/completions"
api_key = "cV4a59t1wjYGs...." # replace with your Mistral API key
# 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"
}
try:
# Make the API request
response = requests.post(api_url, headers=headers, json=payload)
response.raise_for_status()
# 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 in content or content in choice:
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)}"