Skip to Content

AI_ASK

Overview

This function interacts with an AI model to generate text-based responses based on a given prompt. It can optionally incorporate data provided as a 2D list into the prompt for more context-specific analysis or generation.

Usage

To use the AI_ASK function in Excel, enter it as a formula in a cell, specifying your prompt and any optional arguments as needed:

=AI_ASK(prompt, [data], [temperature], [max_tokens], [model], [api_key], [api_url])

Replace each parameter with your desired value. The function returns a text response generated by the AI model.

Parameters

ParameterTypeRequiredDescription
promptstringYesThe question, task, or instruction for the AI.
data2D listNoData from an Excel range to be included in the context sent to the AI.
temperaturefloatNoControls the randomness/creativity of the response (0.0 to 2.0). Higher values mean more creative.
max_tokensintNoMaximum number of tokens (words/subwords) the AI should generate in its response (5 to 5000).
modelstringNoThe specific AI model ID to use for the request (e.g., ‘mistral-small’, ‘mistral-large’).
api_keystringNoAPI key for authentication. Get a free API key from Mistral AI.
api_urlstringNoOpenAI-compatible API endpoint URL which supports CORS. (e.g., https://api.mistral.ai/v1/chat/completions from Mistral AI).

Return Value

Return ValueTypeDescription
ResponsestringThe text response generated by the AI model.

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 response depends on the clarity of the prompt and the data provided.
  • Large data ranges 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 analysis, summarization, and business writing directly in Excel.
  • Saves time and improves consistency in reporting and communication.
  • Enables dynamic, context-aware responses using your own data.
  • More flexible and powerful than manual or native Excel approaches for text generation and analysis.

Examples

Employee Engagement Summary

Ask for a summary of employee engagement survey results.

Sample Input Data (Range A1:B5):

QuestionScore
Team collaboration4.5
Workload3.2
Career advancement3.0
Management support4.0
=AI_ASK("Summarize the key findings from the employee engagement survey:", A1:B5)

Sample Output: “The survey indicates high satisfaction with team collaboration but highlights concerns about workload and career advancement opportunities.”

Quarterly Sales Analysis

Analyze quarterly sales data and provide insights.

Sample Input Data (Range A1:E4):

RegionQ1Q2Q3Q4
North120135150160
South100110120130
Central9095100105
=AI_ASK("Provide a brief analysis of the quarterly sales performance:", A1:E4)

Sample Output: “Sales increased steadily across all regions, with the North region showing the highest growth in Q4.”

Summarize Incident Report

Summarize a block of operational incident text provided in a cell.

Sample Input Text (Cell A1): “On April 10th, a system outage affected order processing for 2 hours. The IT team resolved the issue by updating server configurations. No data loss occurred.”

=AI_ASK("Summarize the following incident report in one sentence:", A1)

Sample Output: “A brief system outage on April 10th was quickly resolved by IT with no data loss.”

Source Code

import requests import json def ai_ask(prompt, data=None, temperature=0.5, max_tokens=250, model='mistral-small-latest', api_key=None, api_url="https://api.mistral.ai/v1/chat/completions"): """ Uses AI to generate responses based on prompts and optional data ranges. Args: prompt (str): The question, task, or analysis to perform data (list, optional): 2D list containing data from Excel range to analyze temperature (float, optional): Controls response creativity (0-2). Default is 0.5 max_tokens (int, optional): Maximum tokens for response generation model (str, optional): ID of the model to use api_key (str, optional): API key for authentication (e.g. for Mistral AI). Get your own free Mistral API key at https://console.mistral.ai/ api_url (str, optional): OpenAI compatible URL. (e.g., https://api.mistral.ai/v1/chat/completions for Mistral AI). Returns: str: The AI-generated response """ # Login on the Functions tab for limited demo usage. 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.") # Construct the message incorporating both prompt and data if provided message = prompt if data is not None: data_str = json.dumps(data, indent=2) message += f"\n\nData to analyze:\n{data_str}" # Prepare the API request payload payload = { "messages": [{"role": "user", "content": message}], "temperature": temperature, "model": model, "max_tokens": max_tokens } headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json", "Accept": "application/json" } # 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)") # 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." response.raise_for_status() # Extract and return the response content response_data = response.json() content = response_data["choices"][0]["message"]["content"] return content
Last updated on