OpenAI API - 嵌入#
SGLang 提供与 OpenAI 兼容的 API,以便从 OpenAI 服务无缝过渡到自托管本地模型。 完整的 API 参考可在 OpenAI API 参考 中找到。
本教程涵盖了嵌入模型的嵌入 API。有关支持的模型列表,请参阅 相应的概览页面
启动服务器#
在您的终端中启动服务器并等待初始化完成。请记住在命令中添加 --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(
"""
python3 -m sglang.launch_server --model-path Alibaba-NLP/gte-Qwen2-1.5B-instruct \
--host 0.0.0.0 --is-embedding --log-level warning
"""
)
wait_for_server(f"http://localhost:{port}")
使用 cURL#
[ ]:
import subprocess, json
text = "从前有一个故事"
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"文本嵌入向量(前10个): {text_embedding[:10]}")
使用 Python 请求#
[ ]:
import requests
text = "从前有一个故事"
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"文本嵌入向量(前10个): {text_embedding[:10]}")
使用 OpenAI Python 客户端#
[ ]:
import openai
client = openai.Client(base_url=f"http://127.0.0.1:{port}/v1", api_key="None")
# 文本嵌入示例
response = client.embeddings.create(
model="Alibaba-NLP/gte-Qwen2-1.5B-instruct",
input=text,
)
embedding = response.data[0].embedding[:10]
print_highlight(f"文本嵌入向量(前10个): {embedding}")
使用输入 ID#
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"输入ID嵌入向量(前10个): {input_ids_embedding[:10]}")
[ ]:
terminate_process(embedding_process)
多模态嵌入模型#
请参阅 多模态嵌入模型