Files
app/lib/ai.ts
Albert 9aa9035d78 fix: Correct OAuth localhost/127.0.0.1 config and fix grapheme counting for Bluesky posts
- Fixed OAuth client configuration to properly use localhost for client_id and 127.0.0.1 for redirect_uris per RFC 8252 and ATproto spec
- Added proper grapheme counting using RichText API instead of character length
- Fixed thread splitting to account for link suffix and thread indicators in grapheme limits
- Added GOOGLE_EMBEDDING_DIMENSIONS env var to all env files
- Added clear-nodes.ts utility script for database management
- Added galaxy node detail page route

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-09 18:26:39 +00:00

43 lines
1.4 KiB
TypeScript

import { GoogleGenerativeAI } from '@google/generative-ai';
// Validate required environment variables
if (!process.env.GOOGLE_GENERATIVE_AI_API_KEY) {
throw new Error('GOOGLE_GENERATIVE_AI_API_KEY environment variable is required');
}
if (!process.env.GOOGLE_EMBEDDING_MODEL) {
throw new Error('GOOGLE_EMBEDDING_MODEL environment variable is required (e.g., gemini-embedding-001)');
}
if (!process.env.GOOGLE_EMBEDDING_DIMENSIONS) {
throw new Error('GOOGLE_EMBEDDING_DIMENSIONS environment variable is required (e.g., 3072)');
}
const genAI = new GoogleGenerativeAI(process.env.GOOGLE_GENERATIVE_AI_API_KEY);
const embeddingModel = genAI.getGenerativeModel({
model: process.env.GOOGLE_EMBEDDING_MODEL,
});
/**
* The expected dimension size for embeddings from the configured model.
* This must match the actual output dimension of the embedding model.
*/
export const EMBEDDING_DIMENSIONS = parseInt(process.env.GOOGLE_EMBEDDING_DIMENSIONS, 10);
/**
* Generates a vector embedding for a given text using the configured Google embedding model.
*
* @param text - The text to embed
* @returns A vector embedding (dimension depends on model)
*/
export async function generateEmbedding(text: string): Promise<number[]> {
try {
const result = await embeddingModel.embedContent(text);
return result.embedding.values;
} catch (error) {
console.error('Error generating embedding:', error);
throw new Error('Failed to generate AI embedding.');
}
}