Text Generation Tutorial

Learn how to generate high-quality text using Lumia AI models.

Step 1: Initial Setup

Setting up your project with Lumia AI

Install the required dependencies:

npm install @ai-sdk/Lumia

Import the necessary modules:

import { generateText } from '@ai-sdk/Lumia';
import { Lumia } from '@ai-sdk/Lumia';

Step 2: Basic Text Generation

Generate your first AI response

Create a basic text generation function:

async function generateBasicText() {
  try {
    const { text } = await generateText({
      model: Lumia('Lumia-V2-Pro'),
      prompt: 'Write a short story about AI',
      system: 'You are a creative writer.'
    });
    
    console.log(text);
  } catch (error) {
    console.error('Error:', error);
  }
}

Step 3: Advanced Parameters

Fine-tune your text generation

Customize the output with advanced parameters:

const response = await generateText({
  model: Lumia('Lumia-V2-Pro'),
  prompt: 'Write a technical blog post about AI',
  system: 'You are an AI expert writing for developers.',
  parameters: {
    temperature: 0.7,    // Controls randomness (0-1)
    maxTokens: 500,      // Maximum length of response
    topP: 0.9,          // Nucleus sampling parameter
    frequencyPenalty: 0.5,  // Reduces repetition
    presencePenalty: 0.5    // Encourages topic diversity
  }
});

Parameter Explanations:

  • temperature: Higher values make output more random, lower more focused
  • maxTokens: Controls the length of generated text
  • topP: Alternative to temperature for controlling randomness
  • frequencyPenalty: Reduces word repetition
  • presencePenalty: Encourages the model to talk about new topics

Step 4: Error Handling

Implement robust error handling

Add proper error handling to your text generation:

async function generateWithErrorHandling() {
  try {
    const { text, usage } = await generateText({
      model: Lumia('Lumia-V2-Pro'),
      prompt: 'Write about AI safety',
      system: 'You are an AI safety researcher.',
    });

    console.log('Generated text:', text);
    console.log('Token usage:', usage);
    
  } catch (error) {
    if (error.name === 'ValidationError') {
      console.error('Invalid parameters:', error.message);
    } else if (error.name === 'RateLimitError') {
      console.error('Rate limit exceeded. Please try again later.');
    } else {
      console.error('Unexpected error:', error);
    }
  }
}

Next Steps

Explore more advanced features

Now that you've mastered the basics, you can:

  • Implement streaming responses
  • Create custom prompt templates
  • Build a text generation UI
  • Integrate with your application