OpenAI 호환 API - Embedding
OpenAI 호환 API - Embedding
텍스트를 벡터로 바꿔야 할 때, SGLang도 OpenAI 호환 임베딩 API를 제공합니다. OpenAI 서비스에서 자체 호스팅 로컬 모델로 옮길 때 API 형태가 같아 전환이 쉽다는 점이 핵심이에요. 이 튜토리얼은 임베딩 모델용 임베딩 API를 다룹니다.
API의 완전한 참조는 OpenAI API Reference에 있어요. 지원되는 모델 목록은 corresponding overview page를 참고하면 됩니다.
서버 실행 (Launch A Server)
터미널에서 서버를 띄우고 초기화를 기다립니다. 네이티브 인코더 구조의 임베딩 아키텍처와 google/embeddinggemma-300m은 자동으로 감지돼요. 디코더 방식의 임베딩 모델은 여전히 --is-embedding을 지정해야 합니다.
from sglang.test.doc_patch import launch_server_cmd
from sglang.utils import wait_for_server, print_highlight, terminate_process
embedding_process, port = launch_server_cmd(
"""
sglang serve --model-path Alibaba-NLP/gte-Qwen2-1.5B-instruct \
--is-embedding --log-level warning
"""
)
wait_for_server(f"http://localhost:{port}")
cURL로 보내기
import subprocess, json
text = "Once upon a time"
curl_text = f"""curl -s http://localhost:{port}/v1/embeddings \
-H "Content-Type: application/json" \
-d '{{"model": "Alibaba-NLP/gte-Qwen2-1.5B-instruct", "input": "{text}"}}'"""
result = subprocess.check_output(curl_text, shell=True)
print(result)
text_embedding = json.loads(result)["data"][0]["embedding"]
print_highlight(f"Text embedding (first 10): {text_embedding[:10]}")
Python requests로 보내기
import requests
text = "Once upon a time"
response = requests.post(
f"http://localhost:{port}/v1/embeddings",
json={"model": "Alibaba-NLP/gte-Qwen2-1.5B-instruct", "input": text},
)
text_embedding = response.json()["data"][0]["embedding"]
print_highlight(f"Text embedding (first 10): {text_embedding[:10]}")
OpenAI Python 클라이언트로 보내기
import openai
client = openai.Client(base_url=f"http://127.0.0.1:{port}/v1", api_key="None")
# Text embedding example
response = client.embeddings.create(
model="Alibaba-NLP/gte-Qwen2-1.5B-instruct",
input=text,
)
embedding = response.data[0].embedding[:10]
print_highlight(f"Text embedding (first 10): {embedding}")
Input IDs로 보내기
SGLang은 임베딩 입력으로 input_ids도 지원합니다.
import json
import os
from transformers import AutoTokenizer
os.environ["TOKENIZERS_PARALLELISM"] = "false"
tokenizer = AutoTokenizer.from_pretrained("Alibaba-NLP/gte-Qwen2-1.5B-instruct")
input_ids = tokenizer.encode(text)
curl_ids = f"""curl -s http://localhost:{port}/v1/embeddings \
-H "Content-Type: application/json" \
-d '{{"model": "Alibaba-NLP/gte-Qwen2-1.5B-instruct", "input": {json.dumps(input_ids)}}}'"""
input_ids_embedding = json.loads(subprocess.check_output(curl_ids, shell=True))["data"][
0
]["embedding"]
print_highlight(f"Input IDs embedding (first 10): {input_ids_embedding[:10]}")
컴팩트한 Base64 응답 (Compact Base64 Responses)
JSON 배열이 응답 크기를 지배할 땐 encoding_format을 base64로 설정할 수 있어요. 인코딩된 값은 리틀엔디언 FP32 값이고, OpenAI 호환 클라이언트로 디코딩할 수 있습니다.
response = requests.post(
f"http://localhost:{port}/v1/embeddings",
json={
"model": "Alibaba-NLP/gte-Qwen2-1.5B-instruct",
"input": text,
"encoding_format": "base64",
},
)
base64_embedding = response.json()["data"][0]["embedding"]
print_highlight(f"Base64 embedding: {base64_embedding[:20]}...")
terminate_process(embedding_process)
멀티모달 임베딩 모델 (Multi-Modal Embedding Model)
Multi-Modal Embedding Model을 참고하세요.
더 알아보기 (Learn more)
- 임베딩 모델을 네이티브
/encode로 쓰는 방법은 SGLang Native APIs를 참고해요. - 지원되는 임베딩 모델 목록은 Embedding models에서 확인할 수 있습니다.