|
| 1 | +import { Index, Pinecone as PineconeClient } from '@pinecone-database/pinecone' |
| 2 | + |
| 3 | +import { connectDB } from '@/models' |
| 4 | +import APICredentials from '@/models/credentials/APICredentials.model' |
| 5 | + |
| 6 | +// Cache for the Pinecone client and index |
| 7 | +let pineconeClientInstance: PineconeClient | null = null |
| 8 | +let pineconeIndexInstance: Index | null = null |
| 9 | +let indexName: string = 'default-index' |
| 10 | + |
| 11 | +/** |
| 12 | + * Initialize the Pinecone client with credentials from the database |
| 13 | + * @returns The Pinecone client instance |
| 14 | + */ |
| 15 | +export const getPineconeClient = async (): Promise<PineconeClient> => { |
| 16 | + // Return cached instance if available |
| 17 | + if (pineconeClientInstance) { |
| 18 | + return pineconeClientInstance |
| 19 | + } |
| 20 | + |
| 21 | + try { |
| 22 | + await connectDB() |
| 23 | + const credentials = await APICredentials.findOne() |
| 24 | + |
| 25 | + if (!credentials || !credentials.providers.pinecone?.apiKey) { |
| 26 | + throw new Error('Pinecone API key not found in database') |
| 27 | + } |
| 28 | + |
| 29 | + // Create a new Pinecone client |
| 30 | + pineconeClientInstance = new PineconeClient({ |
| 31 | + apiKey: credentials.providers.pinecone.apiKey, |
| 32 | + }) |
| 33 | + indexName = |
| 34 | + credentials.providers.pinecone.indexName || |
| 35 | + process.env.PINECONE_INDEX || |
| 36 | + 'default-index' |
| 37 | + |
| 38 | + return pineconeClientInstance |
| 39 | + } catch (error) { |
| 40 | + console.error('Error initializing Pinecone client:', error) |
| 41 | + throw error |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +/** |
| 46 | + * Get the Pinecone index |
| 47 | + * @param indexNameParam Optional index name to override the default |
| 48 | + * @returns The Pinecone index instance |
| 49 | + */ |
| 50 | +export const getPineconeIndex = async ( |
| 51 | + indexNameParam?: string, |
| 52 | +): Promise<Index> => { |
| 53 | + // If index name is provided and different from cached one, reset the index instance |
| 54 | + if (indexNameParam && indexNameParam !== indexName) { |
| 55 | + pineconeIndexInstance = null |
| 56 | + indexName = indexNameParam |
| 57 | + } |
| 58 | + |
| 59 | + // Return cached instance if available |
| 60 | + if (pineconeIndexInstance) { |
| 61 | + return pineconeIndexInstance |
| 62 | + } |
| 63 | + |
| 64 | + try { |
| 65 | + // Get the Pinecone client |
| 66 | + const pineconeClient = await getPineconeClient() |
| 67 | + |
| 68 | + // Create a new Pinecone index |
| 69 | + pineconeIndexInstance = pineconeClient.Index(indexName) |
| 70 | + |
| 71 | + return pineconeIndexInstance |
| 72 | + } catch (error) { |
| 73 | + console.error('Error getting Pinecone index:', error) |
| 74 | + throw error |
| 75 | + } |
| 76 | +} |
0 commit comments