DocumentazioneEmbeddings

Sviluppa

Embeddings

Un embedding traduce un testo in un elenco di numeri. Due testi vicini per significato danno elenchi vicini.

Creare vettori

Invia un testo o un elenco di testi. Ognuno torna con il suo vettore, nello stesso ordine.

passages = [
    "Either party may terminate with three months' notice.",
    "Invoices are payable within thirty days.",
]
result = client.embeddings.create(
    model="learnya-embed", input=passages
)
vectors = [item.embedding for item in result.data]
print(len(vectors), "vectors of", len(vectors[0]), "numbers")
Risposta
{
  "object": "list",
  "model": "learnya-embed",
  "data": [
    { "object": "embedding", "index": 0, "embedding": [0.0123, -0.0481, 0.0277, -0.0019] }
  ],
  "usage": { "prompt_tokens": 9, "total_tokens": 9 }
}

Cercare per significato

Confronta il vettore di una domanda con quelli dei tuoi passaggi. Il più vicino tratta lo stesso tema, anche con altre parole.

import math


def cosine(a, b):
    dot = sum(x * y for x, y in zip(a, b))
    return dot / (
        math.sqrt(sum(x * x for x in a))
        * math.sqrt(sum(y * y for y in b))
    )


question = client.embeddings.create(
    model="learnya-embed",
    input=["Can we end the contract early?"],
)
q = question.data[0].embedding
best = max(
    range(len(passages)), key=lambda i: cosine(q, vectors[i])
)
print(passages[best])