python --version
pip install openai numpy
export OPENAI_API_KEY=sk-...
Use the OpenAI Embeddings API to turn text into dense vectors, then compute cosine similarity to find semantically similar sentences.
1 import numpy as np 2 from openai import OpenAI 3 4 client = OpenAI() 5 6 def embed(text: str) -> list[float]: 7 resp = client.embeddings.create(model="text-embedding-3-small", input=text) 8 return resp.data[0].embedding 9 10 def cosine_similarity(a: list[float], b: list[float]) -> float: 11 va, vb = np.array(a), np.array(b) 12 return float(np.dot(va, vb) / (np.linalg.norm(va) * np.linalg.norm(vb))) 13 14 sentences = [ 15 "How do I boil an egg?", 16 "What temperature for pasta al dente?", 17 "Explain Python decorators", 18 "What is a closure in JavaScript?", 19 "How do I sauté vegetables?", 20 ] 21 22 embeddings = [embed(s) for s in sentences] 23 24 print("Cosine Similarity Matrix:") 25 for i, s1 in enumerate(sentences): 26 for j, s2 in enumerate(sentences): 27 if j > i: 28 sim = cosine_similarity(embeddings[i], embeddings[j]) 29 print(f" [{i}] vs [{j}]: {sim:.3f} ({s1[:30]!r} vs {s2[:30]!r})") 30
Sign in to share your feedback and join the discussion.