Skip to main content

Overview

The generateSubInterests server action uses Google’s Gemini 2.5 Flash model to generate 3-5 highly relevant sub-interests or related topics for a given interest. It includes automatic fallback to mock data if the API key is missing or if an error occurs.

Function Signature

export async function generateSubInterests(interest: string): Promise<string[]>

Parameters

interest
string
required
The main interest or topic to generate sub-interests for. This will be sent to the Gemini API as context for generation.

Returns

subInterests
string[]
An array of 3-5 strings representing related sub-interests or topics. The array is limited to a maximum of 5 items even if the API returns more.

Behavior

API Key Check

The function first checks for the GEMINI_API_KEY environment variable:
  • If missing, logs a warning and returns mock data
  • If present, proceeds with the API call

Response Processing

The function expects a raw JSON array from Gemini (without markdown code blocks):
  1. Removes any \“jsonor```` markdown formatting
  2. Parses the cleaned response as JSON
  3. Validates that the result is an array
  4. Returns up to 5 items from the array

Error Handling

If any error occurs during the API call or response parsing:
  • Logs the error to console
  • Returns fallback mock data based on the input interest

Usage Example

// In a client component (page.tsx:17-39)
const handleSubmit = async (e: React.FormEvent) => {
  e.preventDefault();
  const label = input.trim();
  
  // Create the root node first
  const newNode = addNode(label);
  
  try {
    setIsGenerating(true);
    // Dynamic import for client-side usage
    const { generateSubInterests } = await import('@/app/actions');
    const sub = await generateSubInterests(label);
    useInterestStore.getState().addNodes(sub, newNode.id);
  } catch (err) {
    console.error(err);
  } finally {
    setIsGenerating(false);
  }
};

Mock Data Fallback

When the API key is missing or an error occurs, the function returns:
[
  `${interest} Essentials`,
  `Advanced ${interest}`,
  `${interest} Tools`,
  `${interest} History`
]

Environment Variables

GEMINI_API_KEY
string
required
Google Gemini API key. Required for AI-generated responses. Without this key, the function falls back to mock data.

Error Cases

Error TypeBehavior
Missing API keyReturns mock data, logs warning
Empty responseThrows error, caught by try-catch, returns mock data
Invalid JSONParse error caught, returns mock data
Non-array responseThrows error, returns mock data
Network errorCaught by try-catch, returns mock data

Source Code Location

app/actions.ts:7-47

Build docs developers (and LLMs) love