typescriptintermediate

Google Gemini API Integration

Call the Google Gemini API for text generation with streaming, safety settings, and system prompts.

typescript
import { GoogleGenerativeAI, HarmCategory, HarmBlockThreshold } from '@google/generative-ai';

const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY!);

const model = genAI.getGenerativeModel({
  model: 'gemini-1.5-pro',
  safetySettings: [
    {
      category: HarmCategory.HARM_CATEGORY_HARASSMENT,
      threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
    },
  ],
  systemInstruction: 'You are a helpful coding assistant.',
});

export async function generateText(prompt: string): Promise<string> {
  const result = await model.generateContent(prompt);
  return result.response.text();
}

export async function* streamText(prompt: string): AsyncGenerator<string> {
  const result = await model.generateContentStream(prompt);
  for await (const chunk of result.stream) {
    yield chunk.text();
  }
}

Use Cases

  • Google AI-powered code generation
  • Streaming chat responses
  • Multi-modal content analysis

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.