typescriptintermediate
Google Gemini API Integration
Call the Google Gemini API for text generation with streaming, safety settings, and system prompts.
typescriptPress ⌘/Ctrl + Shift + C to copy
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.
typescriptintermediate
OpenAI Chat Completion with Streaming
Stream GPT responses token-by-token using the OpenAI SDK with async iteration.
Best for: chatbot UI
#openai#streaming
typescriptadvanced
RAG Pipeline (Retrieve + Augment + Generate)
Minimal RAG implementation: embed a query, retrieve top-k chunks, inject into prompt.
Best for: document Q&A
#rag#embeddings
typescriptbeginner
Claude Messages API (Anthropic SDK)
Send messages to Claude using the official Anthropic SDK with system prompt and user turn.
Best for: AI assistant
#anthropic#claude
pythonbeginner
LangChain Prompt Chain (Python)
Build a simple LLMChain with a prompt template and ChatOpenAI in LangChain.
Best for: prompt chaining
#langchain#openai