
Hướng Dẫn API Text-Embedding-3-Small - Cẩm Nang Mô Hình Embedding OpenAI
Đang xây dựng công cụ tìm kiếm ngữ nghĩa hoặc hệ thống RAG (Retrieval-Augmented Generation)? Text-embedding-3-small là mô hình embedding mới nhất của OpenAI, chuyển văn bản thành các vector số, cho phép tìm kiếm tương đồng và truy xuất nội dung mạnh mẽ.
Trong hướng dẫn này, bạn sẽ học được:
- Embedding văn bản là gì và tại sao chúng quan trọng
- Cách sử dụng API text-embedding-3-small
- Ví dụ mã hoàn chỉnh bằng Python và Node.js
- Tùy chỉnh số chiều để tối ưu lưu trữ
- So sánh giá và tối ưu chi phí
What is Text-Embedding-3-Small?#
Text-embedding-3-small là mô hình embedding gọn nhẹ của OpenAI, phát hành tháng 1/2024. Nó chuyển văn bản thành các vector 1536 chiều nắm bắt ý nghĩa ngữ nghĩa, cho phép:
- Semantic Search: Tìm tài liệu liên quan dựa trên ý nghĩa, không chỉ từ khóa
- RAG Systems: Truy xuất ngữ cảnh cho phản hồi LLM
- Similarity Matching: So sánh mức độ tương đồng văn bản cho hệ gợi ý
- Clustering: Gom nhóm các tài liệu tương tự
- Classification: Phân loại văn bản dựa trên nội dung
Model Specifications#
| Specification | Value |
|---|---|
| Model Name | text-embedding-3-small |
| Default Dimensions | 1536 |
| Custom Dimensions | 256, 512, 1024, 1536 |
| Max Input Tokens | 8,191 |
| Output | Normalized vector |
Quick Start#
Prerequisites#
- Đăng ký tại Crazyrouter
- Lấy API key từ dashboard
- Python 3.8+ hoặc Node.js 16+
Python Example#
from openai import OpenAI
client = OpenAI(
api_key="your-crazyrouter-api-key",
base_url="https://crazyrouter.com/v1"
)
# Generate embedding for a single text
response = client.embeddings.create(
model="text-embedding-3-small",
input="Machine learning is transforming industries worldwide."
)
embedding = response.data[0].embedding
print(f"Dimensions: {len(embedding)}") # Output: 1536
print(f"First 5 values: {embedding[:5]}")
Node.js Example#
import OpenAI from 'openai';
const client = new OpenAI({
apiKey: 'your-crazyrouter-api-key',
baseURL: 'https://crazyrouter.com/v1'
});
async function getEmbedding(text) {
const response = await client.embeddings.create({
model: 'text-embedding-3-small',
input: text
});
return response.data[0].embedding;
}
// Usage
const embedding = await getEmbedding('Machine learning is amazing');
console.log(`Dimensions: ${embedding.length}`); // Output: 1536
cURL Example#
curl -X POST https://crazyrouter.com/v1/embeddings \
-H "Authorization: Bearer your-api-key" \
-H "Content-Type: application/json" \
-d '{
"model": "text-embedding-3-small",
"input": "Hello world"
}'
Response:
{
"object": "list",
"model": "text-embedding-3-small",
"usage": {
"prompt_tokens": 2,
"total_tokens": 2
},
"data": [
{
"object": "embedding",
"index": 0,
"embedding": [-0.0020785425, -0.049085874, 0.02094679, ...]
}
]
}
Batch Embedding#
Xử lý nhiều đoạn văn bản trong một lần gọi API để hiệu quả hơn:
from openai import OpenAI
client = OpenAI(
api_key="your-crazyrouter-api-key",
base_url="https://crazyrouter.com/v1"
)
# Batch embedding - multiple texts at once
texts = [
"Python is a programming language",
"JavaScript runs in browsers",
"Machine learning uses neural networks"
]
response = client.embeddings.create(
model="text-embedding-3-small",
input=texts
)
# Access each embedding
for i, data in enumerate(response.data):
print(f"Text {i}: {len(data.embedding)} dimensions")
# Output:
# Text 0: 1536 dimensions
# Text 1: 1536 dimensions
# Text 2: 1536 dimensions
Custom Dimensions#
Giảm chi phí lưu trữ bằng cách dùng số chiều nhỏ hơn. Mô hình hỗ trợ giảm chiều mà vẫn giữ chất lượng tốt:
# Use 512 dimensions instead of 1536
response = client.embeddings.create(
model="text-embedding-3-small",
input="Your text here",
dimensions=512 # Options: 256, 512, 1024, 1536
)
embedding = response.data[0].embedding
print(f"Dimensions: {len(embedding)}") # Output: 512
Dimension Comparison#
| Dimensions | Storage (per vector) | Use Case |
|---|---|---|
| 256 | 1 KB | Ứng dụng mobile, lưu trữ hạn chế |
| 512 | 2 KB | Hiệu năng và chi phí cân bằng |
| 1024 | 4 KB | Nhu cầu độ chính xác cao |
| 1536 | 6 KB | Độ chính xác tối đa |
Building a Semantic Search System#
Dưới đây là ví dụ hoàn chỉnh xây dựng hệ thống tìm kiếm ngữ nghĩa:
import numpy as np
from openai import OpenAI
client = OpenAI(
api_key="your-crazyrouter-api-key",
base_url="https://crazyrouter.com/v1"
)
def get_embedding(text):
"""Get embedding for a single text"""
response = client.embeddings.create(
model="text-embedding-3-small",
input=text
)
return response.data[0].embedding
def cosine_similarity(a, b):
"""Calculate cosine similarity between two vectors"""
return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
# Document database
documents = [
"Python is great for data science and machine learning",
"JavaScript is essential for web development",
"Docker containers simplify deployment",
"Kubernetes orchestrates container workloads",
"PostgreSQL is a powerful relational database"
]
# Pre-compute embeddings for all documents
doc_embeddings = [get_embedding(doc) for doc in documents]
# Search function
def search(query, top_k=3):
query_embedding = get_embedding(query)
# Calculate similarities
similarities = [
cosine_similarity(query_embedding, doc_emb)
for doc_emb in doc_embeddings
]
# Get top results
results = sorted(
zip(documents, similarities),
key=lambda x: x[1],
reverse=True
)[:top_k]
return results
# Example search
results = search("How to deploy applications?")
for doc, score in results:
print(f"Score: {score:.4f} - {doc}")
# Output:
# Score: 0.8234 - Docker containers simplify deployment
# Score: 0.7891 - Kubernetes orchestrates container workloads
# Score: 0.6543 - PostgreSQL is a powerful relational database
Integration with Vector Databases#
Pinecone Integration#
import pinecone
from openai import OpenAI
# Initialize clients
client = OpenAI(
api_key="your-crazyrouter-api-key",
base_url="https://crazyrouter.com/v1"
)
pinecone.init(api_key="your-pinecone-key")
index = pinecone.Index("your-index")
def embed_and_upsert(texts, ids):
"""Embed texts and store in Pinecone"""
response = client.embeddings.create(
model="text-embedding-3-small",
input=texts
)
vectors = [
(id, data.embedding)
for id, data in zip(ids, response.data)
]
index.upsert(vectors=vectors)
def search_pinecone(query, top_k=5):
"""Search Pinecone with query embedding"""
response = client.embeddings.create(
model="text-embedding-3-small",
input=query
)
results = index.query(
vector=response.data[0].embedding,
top_k=top_k
)
return results
ChromaDB Integration#
import chromadb
from openai import OpenAI
client = OpenAI(
api_key="your-crazyrouter-api-key",
base_url="https://crazyrouter.com/v1"
)
# Initialize ChromaDB
chroma_client = chromadb.Client()
collection = chroma_client.create_collection("documents")
def get_embeddings(texts):
"""Get embeddings for multiple texts"""
response = client.embeddings.create(
model="text-embedding-3-small",
input=texts
)
return [data.embedding for data in response.data]
# Add documents
documents = ["doc1 content", "doc2 content", "doc3 content"]
embeddings = get_embeddings(documents)
collection.add(
embeddings=embeddings,
documents=documents,
ids=["doc1", "doc2", "doc3"]
)
# Query
query_embedding = get_embeddings(["search query"])[0]
results = collection.query(
query_embeddings=[query_embedding],
n_results=3
)
Available Embedding Models#
Crazyrouter cung cấp quyền truy cập nhiều mô hình embedding của OpenAI:
| Model | Dimensions | Price Ratio | Best For |
|---|---|---|---|
text-embedding-3-small | 1536 | 0.01 | Dùng chung, tối ưu chi phí |
text-embedding-3-large | 3072 | 0.065 | Nhu cầu độ chính xác rất cao |
text-embedding-ada-002 | 1536 | 0.05 | Tương thích hệ thống cũ |
Pricing Comparison#
| Provider | Model | Price per 1M tokens |
|---|---|---|
| OpenAI Official | text-embedding-3-small | $0.020 |
| Crazyrouter | text-embedding-3-small | $0.002 |
| OpenAI Official | text-embedding-3-large | $0.130 |
| Crazyrouter | text-embedding-3-large | $0.013 |
Pricing Disclaimer: Giá hiển thị chỉ dùng minh họa và có thể thay đổi. Hóa đơn thực tế dựa trên giá thời gian thực tại thời điểm yêu cầu.
Ví dụ tiết kiệm chi phí:
Với hệ thống RAG xử lý 10M tokens/tháng:
- OpenAI Official: $200/tháng
- Crazyrouter: $20/tháng
- Tiết kiệm: 90%
Best Practices#
1. Batch Your Requests#
# Good - single API call for multiple texts
response = client.embeddings.create(
model="text-embedding-3-small",
input=["text1", "text2", "text3"] # Up to 2048 texts
)
# Bad - multiple API calls
for text in texts:
response = client.embeddings.create(
model="text-embedding-3-small",
input=text
)
2. Cache Embeddings#
import hashlib
import json
embedding_cache = {}
def get_embedding_cached(text):
# Create cache key
cache_key = hashlib.md5(text.encode()).hexdigest()
if cache_key in embedding_cache:
return embedding_cache[cache_key]
response = client.embeddings.create(
model="text-embedding-3-small",
input=text
)
embedding = response.data[0].embedding
embedding_cache[cache_key] = embedding
return embedding
3. Use Appropriate Dimensions#
- 256 dimensions: Ứng dụng mobile, thiết bị IoT
- 512 dimensions: Ứng dụng web với hạn chế lưu trữ
- 1024 dimensions: Ứng dụng tiêu chuẩn
- 1536 dimensions: Yêu cầu độ chính xác tối đa
Frequently Asked Questions#
What's the difference between text-embedding-3-small and text-embedding-3-large?#
Text-embedding-3-small tạo ra vector 1536 chiều và được tối ưu cho chi phí. Text-embedding-3-large tạo ra vector 3072 chiều với độ chính xác cao hơn nhưng chi phí gấp khoảng 6,5 lần. Với hầu hết ứng dụng, text-embedding-3-small đã cho kết quả rất tốt.
Can I reduce dimensions after generating embeddings?#
Có, bạn có thể dùng tham số dimensions để tạo trực tiếp vector nhỏ hơn. Cách này hiệu quả hơn so với việc tạo vector đầy đủ rồi tự cắt giảm.
How many texts can I embed in one request?#
Bạn có thể embed tối đa 2048 đoạn văn bản trong một yêu cầu API. Với bộ dữ liệu lớn, hãy chia batch theo nhóm 2048.
Are the embeddings normalized?#
Có, text-embedding-3-small trả về các vector đã được chuẩn hóa (độ dài đơn vị), nên bạn có thể dùng dot product thay cho cosine similarity để tính toán nhanh hơn.
Getting Started#
- Đăng ký tại Crazyrouter
- Lấy API key từ dashboard
- Cài SDK:
pip install openaihoặcnpm install openai - Bắt đầu tạo embedding với các ví dụ mã ở trên
Bài viết liên quan:
Nếu có câu hỏi, liên hệ: support@crazyrouter.com


