OpenAI Embedding
OpenAI Embedding
OpenAI's text embedding API. Includes text-embedding-ada-002 and others.
OpenAI Embedding
OpenAI's text embedding API. Includes text-embedding-ada-002 and others.
OpenAI Embedding is an API service that converts text into high-dimensional vectors (arrays of numbers). These vectors represent the meaning of text numerically, so texts with similar meanings are located close to each other in the vector space. It is used as a core component in semantic search, RAG, recommendation systems, clustering, and more.
It became widely adopted with the release of text-embedding-ada-002 in 2022, and the release of text-embedding-3-small/large in 2024 significantly improved performance and cost efficiency. The text-embedding-3 series allows the vector size to be adjusted with the dimensions parameter, making it possible to optimize storage space.
Embedding makes it possible to compare text based on meaning. Unlike keyword search, it recognizes that "puppy" and "pet dog" are similar, and can distinguish "Apple the company" from "apple the fruit." Cosine similarity is used to measure the distance between vectors.
The most common use in practice is RAG (Retrieval-Augmented Generation). Documents are converted into embeddings and stored in a vector DB, and when a question comes in, similar documents are retrieved and provided to the LLM as context. text-embedding-3-small costs $0.02/1M tokens and is sufficient for most uses; if high quality is needed, use text-embedding-3-large ($0.13/1M).
# OpenAI Embedding API 사용 예제
# pip install openai numpy
from openai import OpenAI
import numpy as np
client = OpenAI()
# ===== 1. 기본 임베딩 생성 =====
response = client.embeddings.create(
model="text-embedding-3-small",
input="인공지능은 미래 기술의 핵심입니다."
)
embedding = response.data[0].embedding
print(f"임베딩 차원: {len(embedding)}") # 1536
# ===== 2. 배치 임베딩 (여러 텍스트) =====
texts = [
"강아지는 귀엽습니다.",
"반려견과 함께 산책했어요.",
"오늘 날씨가 좋습니다."
]
response = client.embeddings.create(
model="text-embedding-3-small",
input=texts
)
embeddings = [item.embedding for item in response.data]
print(f"생성된 임베딩 수: {len(embeddings)}")
# ===== 3. 차원 축소 (비용/저장 최적화) =====
response = client.embeddings.create(
model="text-embedding-3-small",
input="테스트 문장입니다.",
dimensions=512 # 기본 1536에서 512로 축소
)
print(f"축소된 차원: {len(response.data[0].embedding)}") # 512
# ===== 4. 코사인 유사도 계산 =====
def cosine_similarity(a, b):
return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
# 유사도 비교
query = "귀여운 강아지"
query_emb = client.embeddings.create(
model="text-embedding-3-small",
input=query
).data[0].embedding
for i, text in enumerate(texts):
similarity = cosine_similarity(query_emb, embeddings[i])
print(f"'{text}' 유사도: {similarity:.4f}")
# 출력:
# '강아지는 귀엽습니다.' 유사도: 0.8912
# '반려견과 함께 산책했어요.' 유사도: 0.7234
# '오늘 날씨가 좋습니다.' 유사도: 0.3456
# ===== 5. RAG용 문서 검색 함수 =====
def find_similar_documents(query, documents, top_k=3):
"""쿼리와 가장 유사한 문서 top_k개 반환"""
# 쿼리 임베딩
query_emb = client.embeddings.create(
model="text-embedding-3-small",
input=query
).data[0].embedding
# 문서 임베딩 (실제로는 미리 계산해서 DB에 저장)
doc_embeddings = client.embeddings.create(
model="text-embedding-3-small",
input=documents
)
# 유사도 계산 및 정렬
similarities = []
for i, doc_emb in enumerate(doc_embeddings.data):
sim = cosine_similarity(query_emb, doc_emb.embedding)
similarities.append((i, sim, documents[i]))
similarities.sort(key=lambda x: x[1], reverse=True)
return similarities[:top_k]
# 사용 예시
# results = find_similar_documents("AI 기술", documents)
"Just use text-embedding-3-small for document search. At $0.02/1M tokens, embedding 1 million documents costs about $20, and reducing it to dimensions=512 cuts vector DB costs in half. The accuracy loss is under 5%."
"OpenAI Embedding converts the meaning of text into high-dimensional vectors. The text-embedding-3 series ranks near the top of the MTEB benchmark, and the dimensions parameter can be adjusted between 256 and 3072. In RAG, chunked documents are embedded and stored in a vector DB, and retrieved by cosine similarity with the query."
"If search accuracy is low, it may be a chunk size issue. A 512-token chunk with 128-token overlap is a common starting point, and it needs to be adjusted depending on the domain. Switching to the large model improves performance by about 10%, but the cost is 6 times higher."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
An embedding does not change once it is generated. Be sure to store it in a vector DB (Pinecone, Chroma, etc.) and reuse it.
text-embedding-3 supports a maximum of 8191 tokens. Long documents must be chunked into appropriately sized pieces.
Chunk documents into appropriate sizes → generate embeddings → store in a vector DB → retrieve similar documents at query time. Using the Batch API can reduce costs by 50%.