AI_LIST
Overview
The AI_LIST
function generates a list of items using an AI model based on a user-provided prompt. It is useful for categorization, classification, and matching tasks, such as assigning items to categories or generating business lists from context. The function is compatible with OpenAI-style APIs that support JSON output, such as Mistral AI (docs ). This example function is provided as-is without any representation of accuracy.
Usage
Use the function in Excel as follows:
=AI_LIST(prompt, [values], [temperature], [max_tokens], [model], [api_key], [api_url])
prompt
(string, required): Instruction describing the list the AI should create.values
(2D list, optional, default=None): Data from an Excel range to include as context.temperature
(float, optional, default=0.0): Controls randomness/creativity (0.0 to 2.0).max_tokens
(int, optional, default=1000): Maximum number of tokens to generate (5 to 5000).model
(string, optional, default=“mistral-small-latest”): Model ID to use.api_key
(string, optional): API key for authentication.api_url
(string, optional, default=“https://api.mistral.ai/v1/chat/completions ”): API endpoint URL.
The function returns a single-column 2D list of items generated by the AI model. On error, it returns a 2D list with an error message string.
Examples
Example 1: Generate Marketing KPIs
=AI_LIST("List essential marketing KPIs for quarterly performance reviews")
Expected output:
Customer Acquisition Cost |
Conversion Rate |
Return on Marketing Investment |
Customer Lifetime Value |
Website Traffic |
Social Media Engagement |
Email Open Rate |
Marketing Qualified Leads |
Example 2: Risk Mitigation Strategies
=AI_LIST("List effective risk mitigation strategies for enterprise software implementation")
Expected output:
Phased Implementation Approach |
Comprehensive Testing Protocol |
Stakeholder Engagement Plan |
Clear Change Management Process |
Dedicated Support Team |
Regular Progress Reviews |
Vendor SLA Enforcement |
Data Backup and Recovery Plan |
Example 3: Using Values Parameter
Sample values (range A1:A3
):
Q1 revenue fell 5% below target |
Customer complaints increased by 12% |
New product launch delayed by 3 weeks |
=AI_LIST("List priority action items based on these quarterly business review notes:", A1:A3)
Expected output:
Perform revenue gap analysis |
Implement customer feedback process improvements |
Review and optimize product development workflow |
Conduct sales team performance evaluation |
Develop enhanced customer satisfaction strategy |
Revise product launch timeline and accountability |
Python Code
import requests
import json
def ai_list(prompt, values=None, temperature=0.0, max_tokens=1000, model="mistral-small-latest", api_key=None, api_url="https://api.mistral.ai/v1/chat/completions"):
"""
Generate a list of items using an AI model based on a prompt and optional context values.
Args:
prompt (str): Instruction describing the list to generate.
values (list, optional): 2D list of context data to include. Default is None.
temperature (float, optional): Randomness/creativity (0.0 to 2.0). Default is 0.0.
max_tokens (int, optional): Maximum tokens to generate (5 to 5000). Default is 1000.
model (str, optional): Model ID to use. Default is "mistral-small-latest".
api_key (str, optional): API key for authentication.
api_url (str, optional): API endpoint URL. Default is "https://api.mistral.ai/v1/chat/completions".
Returns:
list: 2D list (single column) of items, or 2D list with error message string on failure.
This example function is provided as-is without any representation of accuracy.
"""
# Use Boardflare demo if api_key or api_url not provided
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."]]
# Validate 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)"]]
# Validate max_tokens
if not isinstance(max_tokens, int) or not (5 <= max_tokens <= 5000):
return [["Error: max_tokens must be an integer between 5 and 5000 (inclusive)"]]
# Build prompt
list_prompt = f"Generate a list based on this request: {prompt}"
if values is not None:
values_str = "\n".join([str(item[0]) for item in values]) if len(values) > 0 and len(values[0]) > 0 else ""
if values_str:
list_prompt += f"\n\nUse this information to help create the list:\n{values_str}"
list_prompt += "\nReturn ONLY a JSON object with a key 'items' whose value is a JSON array of the items for the list. "
list_prompt += "Each item should be a single value. "
list_prompt += "Do not include any explanatory text, just the JSON object. "
list_prompt += 'For example: {"items": ["item1", "item2", "item3"]}'
# Prepare payload
payload = {
"messages": [{"role": "user", "content": list_prompt}],
"temperature": temperature,
"model": model,
"max_tokens": max_tokens,
"response_format": {"type": "json_object"}
}
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"Accept": "application/json"
}
# Make 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.raise_for_status()
response_data = response.json()
content = response_data["choices"][0]["message"]["content"]
try:
list_data = json.loads(content)
if isinstance(list_data, dict) and "items" in list_data:
list_data = list_data["items"]
elif isinstance(list_data, dict):
for key, value in list_data.items():
if isinstance(value, list):
list_data = value
break
if isinstance(list_data, list):
result = []
for item in list_data:
if isinstance(item, list):
if len(item) >= 1:
result.append([str(item[0])])
else:
result.append([""])
else:
result.append([str(item)])
return result
else:
return [["Error: Unable to parse response. Expected a list."]]
except (json.JSONDecodeError, ValueError):
return [["Error: Unable to generate list. The AI response wasn't in the expected format."]]
except requests.exceptions.RequestException as e:
return [["Error: API request failed.", str(e)]]
Live Notebook
Edit this function in a live notebook .