user39063
user39063

Reputation: 325

OpenAI Embeddings API: How to extract the embedding vector?

I use nearly the same code as here in this GitHub repo to get embeddings from OpenAI:

oai = OpenAI(
# This is the default and can be omitted
api_key="sk-.....",
)

def get_embedding(text_to_embed, openai):
   
    response = openai.embeddings.create(
        model= "text-embedding-ada-002",
        input=[text_to_embed]
    )
    
    return response

embedding_raw = get_embedding(text,oai)

According to the GitHub repo, the vector should be in response['data'][0]['embedding']. But it isn't in my case.

When I printed the response variable, I got this:

print(embedding_raw)

Output:

CreateEmbeddingResponse(data=[Embedding(embedding=[0.009792150929570198, -0.01779201813042164, 0.011846082285046577, -0.0036859565880149603, -0.0013213189085945487, 0.00037509595858864486,..... -0.0121011883020401, -0.015751168131828308], index=0, object='embedding')], model='text-embedding-ada-002', object='list', usage=Usage(prompt_tokens=360, total_tokens=360))

How can I access the embedding vector?

Upvotes: 4

Views: 3631

Answers (1)

Rok Benko
Rok Benko

Reputation: 23060

Simply return just the embedding vector as follows:

def get_embedding(text_to_embed, openai):
   
    response = openai.embeddings.create(
        model= "text-embedding-ada-002",
        input=[text_to_embed]
    )
    
    return response.data[0].embedding # Change this

embedding_raw = get_embedding(text,oai)

Upvotes: 2

Related Questions