兼容 Ollama 的 API#
SGLang 提供了 Ollama API 兼容性,允许您将 SGLang 作为推理后端来使用 Ollama CLI 和 Python 库。
前提条件#
# Install the Ollama Python library (for Python client usage)
pip install ollama
注意:您不需要安装 Ollama 服务端 —— SGLang 充当后端。您只需要
ollamaCLI 或 Python 库作为客户端。
端点#
端点 |
方法 |
描述 |
|---|---|---|
|
GET, HEAD |
针对 Ollama CLI 的健康检查 |
|
GET |
列出可用模型 |
|
POST |
聊天补全(流式与非流式) |
|
POST |
文本生成(流式与非流式) |
|
POST |
模型信息 |
快速入门#
1. 启动 SGLang 服务端#
python -m sglang.launch_server \
--model Qwen/Qwen2.5-1.5B-Instruct \
--port 30001 \
--host 0.0.0.0
注意:在
ollama run中使用的模型名称必须与您传递给--model的名称完全一致。
2. 使用 Ollama CLI#
# List available models
OLLAMA_HOST=https://:30001 ollama list
# Interactive chat
OLLAMA_HOST=https://:30001 ollama run "Qwen/Qwen2.5-1.5B-Instruct"
如果连接到防火墙后的远程服务器
# SSH tunnel
ssh -L 30001:localhost:30001 user@gpu-server -N &
# Then use Ollama CLI as above
OLLAMA_HOST=https://:30001 ollama list
3. 使用 Ollama Python 库#
import ollama
client = ollama.Client(host='https://:30001')
# Non-streaming
response = client.chat(
model='Qwen/Qwen2.5-1.5B-Instruct',
messages=[{'role': 'user', 'content': 'Hello!'}]
)
print(response['message']['content'])
# Streaming
stream = client.chat(
model='Qwen/Qwen2.5-1.5B-Instruct',
messages=[{'role': 'user', 'content': 'Tell me a story'}],
stream=True
)
for chunk in stream:
print(chunk['message']['content'], end='', flush=True)
智能路由 (Smart Router)#
关于使用 LLM 评判器在本地 Ollama(快速)和远程 SGLang(强大)之间进行智能路由的信息,请参阅 Smart Router 文档。
总结#
组件 |
用途 |
|---|---|
Ollama API |
开发者熟悉的 CLI/API |
SGLang 后端 |
高性能推理引擎 |
智能路由 (Smart Router) |
智能路由 - 简单任务使用快速的本地端,复杂任务使用强大的远程端 |