Im transitioning from js to ts and experimenting with the embedding API of OpenAI.
My goal here is to get the array values of the "embedding" key from the JSON response & store it on a variable, simple as that, the problem is i haven't been able to actually do this since yesterday and im loosing my mind:
The code:
// Generate Embeddings
async function generateEmbed(text:string): Promise<void> {
const url = 'https://api.openai.com/v1/embeddings';
const model = 'text-embedding-ada-002'; // Replace with the ID of the model you want to use
const input = text;
const requestBody = {
model,
input
};
//
//console.log(requestBody);
//
try {
const API_KEY = 'XXXX-XXX-XXX-VALIDKEY'; // test purposes
const response = await axios.post(url, requestBody, {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${API_KEY}`
}
});
const embedding: string = response.data[2].text;
console.log('Result:', embedding);
} catch (error) {
console.error(error);
}
}
This prints:
TypeError: Cannot read properties of undefined (reading 'text')
The example JSON response is:
{
"object": "list",
"data": [
{
"object": "embedding",
"index": 0,
"embedding": [
-0.0030878915,
0.008527344,
0.0036363655,
-0.05539084,
-0.04473669,
0.03561223,
0.015806785,
0.0021955732,
-0.0052868193,
0.011660523,
-0.012861462,
0.026071802,
0.00896344,
0.002973836,
0.0025729635
]
}
],
"model": "text-embedding-ada-002-v2",
"usage": {
"prompt_tokens": 58,
"total_tokens": 58
}
}
I think it's clear it has something to do with the type, but I've been trying to get that embedding key values with no luck, so any bit of help would be very appreciate.
I tried approching this using a few alternatives:
classic
const embedding: string = response.data;
console.log('Result:', embedding);
logs:
Result: {
object: 'list',
data: [ { object: 'embedding', index: 0, embedding: [Array] } ],
model: 'text-embedding-ada-002-v2',
usage: { prompt_tokens: 1, total_tokens: 1 }
}
**The shared above **
const embedding: string = response.data[2].text;
console.log('Result:', embedding);
Which gets the undefined value.
**my most desesperate attempt with no luck: **
const embedding: any = response.data[2];
console.log('Result:', embedding);
Returns:
Result: undefined
Im expecting getting the values of the embedding array and store them in the variable embedding.
Expected output:
[
-0.0030878915,
0.008527344,
0.0036363655,
-0.05539084,
-0.04473669,
0.03561223,
0.015806785,
0.0021955732,
-0.0052868193,
0.011660523,
-0.012861462,
0.026071802,
0.00896344,
0.002973836,
0.0025729635
]
Variable:
embedding = [
-0.0030878915,
0.008527344,
0.0036363655,
-0.05539084,
-0.04473669,
0.03561223,
0.015806785,
0.0021955732,
-0.0052868193,
0.011660523,
-0.012861462,
0.026071802,
0.00896344,
0.002973836,
0.0025729635
]
Will appreciate any help on this!