File size: 1,669 Bytes
e6b7161 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
import { PineconeClient } from "@pinecone-database/pinecone";
import * as dotenv from "dotenv";
dotenv.config();
const indexName = process.env.INDEX_NAME;
const pineconeClient = new PineconeClient();
await pineconeClient.init({
apiKey: process.env.PINECONE_API_KEY,
environment: process.env.PINECONE_ENVIRONMENT,
});
const saveEmbedding = async ({ id, values, metadata, namespace }) => {
const index = pineconeClient.Index(indexName);
const upsertRequest = {
vectors: [
{
id,
values,
metadata,
},
],
namespace,
};
try {
const response = await index.upsert({ upsertRequest });
return response?.upsertedCount > 0
? {
message: "training",
}
: {
message: "failed training",
};
} catch (e) {
console.log("failed", e);
}
};
const queryEmbedding = async ({ values, namespace }) => {
const index = pineconeClient.Index(indexName);
const queryRequest = {
topK: 1,
vector: values,
includeMetadata: true,
namespace,
};
try {
const response = await index.query({ queryRequest });
const match = response.matches[0];
const metadata = match?.metadata;
const score = match?.score;
return {
label: metadata?.label || "Unknown",
confidence: score,
};
} catch (e) {
console.log("failed", e);
}
};
const deleteNamespace = async ({ namespace }) => {
const index = pineconeClient.Index(indexName);
try {
await index.delete1({
deleteAll: true,
namespace,
});
} catch (e) {
console.log("failed", e);
}
};
export { saveEmbedding, queryEmbedding, deleteNamespace }; |