Skip to Content

AI_CHOICE

Overview

AI_CHOICE uses AI to classify or select the most appropriate option from a list of choices based on provided text. It is ideal for categorization, sentiment analysis, prioritization, and other decision-making tasks where multiple options must be evaluated against a text description. The function leverages Mistral AI’s large language models via their API.

Relevant links:

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

Usage

To use the function in Excel:

=AI_CHOICE(text, choices, [temperature], [model], [api_key], [api_url])
  • text (str or 2D list, required): The text to classify or analyze.
  • choices (str or 2D list, required): The options to choose from (comma-separated string or range with one option per cell).
  • temperature (float, optional, default=0.2): Controls the randomness/creativity of the response (0.0 to 2.0). Higher values mean more creative.
  • model (str, optional, default=“mistral-small-latest”): The specific AI model ID to use for the request.
  • api_key (str, optional): API key for authentication. Get a free API key from Mistral AI.
  • api_url (str, optional, default=“https://api.mistral.ai/v1/chat/completions”): OpenAI-compatible API endpoint URL which supports CORS.

The function returns the selected choice from the provided options as a string. If input is invalid or an error occurs, a string error message is returned instead.

Examples

Example 1: Expense Categorization

This example classifies an expense description into a category.

In Excel:

=AI_CHOICE("Uber ride from airport to hotel, $45.50", {"Travel","Food","Office","Software"})

Expected output:

Result
Travel

Example 2: Email Sentiment Analysis

This example classifies the sentiment of an email.

In Excel:

=AI_CHOICE("I've been waiting for a response about my refund for over two weeks now. This is completely unacceptable...", {"Positive","Neutral","Negative"})

Expected output:

Result
Negative

This means the function selected the most appropriate choice from the provided options based on the input text.

Python Code

import requests import json 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: The context, question, or scenario used for decision-making. Accepts a string or a 2D list of strings. choices: The options to choose from. Accepts a comma-separated string or a 2D list of strings. temperature: Controls randomness in the selection (0-2). Default is 0.2. model: ID of the AI model to use. Default is "mistral-small-latest". api_key: API key for authentication (e.g. for Mistral AI). Optional. api_url: OpenAI-compatible URL. Default is "https://api.mistral.ai/v1/chat/completions". Returns: The selected choice from the options provided as a string, or an error message string if input is invalid. This example function is provided as-is without any representation of accuracy. """ # 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): 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)}"
Last updated on