튜토리얼: 요청 보내기

튜토리얼: 요청 보내기 (Sending a Request)

SGLang을 설치하고 나서 바로 채팅 컴플리션을 써보고 싶다면, 이 글이 출발점이에요. 서버만 떠 있으면 API 문서도 함께 제공되니, Swagger UI(/docs)나 ReDoc(/redoc), OpenAPI 스펙(/openapi.json)을 열어 언제든 파라미터를 확인할 수 있어요.

출처: 공식 문서 - Sending a request

비전 언어 모델을 쓰고 싶다면 OpenAI APIs - Vision, 임베딩 모델은 OpenAI APIs - EmbeddingEncode (embedding model)을, 리워드 모델은 Classify (reward model)을 각각 참고하면 됩니다.

서버 실행 (Launch A Server)

from sglang.test.doc_patch import launch_server_cmd
from sglang.utils import wait_for_server, terminate_process

# This is equivalent to running the following command in your terminal
# python3 -m sglang.launch_server --model-path qwen/qwen2.5-0.5b-instruct --host 0.0.0.0

server_process, port = launch_server_cmd(
    """
python3 -m sglang.launch_server --model-path qwen/qwen2.5-0.5b-instruct \
 --host 0.0.0.0 --log-level warning
"""
)

wait_for_server(f"http://localhost:{port}")

cURL로 보내기

import subprocess, json

curl_command = f"""
curl -s http://localhost:{port}/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{{"model": "qwen/qwen2.5-0.5b-instruct", "messages": [{{"role": "user", "content": "What is the capital of France?"}}]}}'
"""

response = json.loads(subprocess.check_output(curl_command, shell=True))
print(response)

Python requests로 보내기

import requests

url = f"http://localhost:{port}/v1/chat/completions"

data = {
    "model": "qwen/qwen2.5-0.5b-instruct",
    "messages": [{"role": "user", "content": "What is the capital of France?"}],
}

response = requests.post(url, json=data)
print(response.json())

OpenAI Python 클라이언트로 보내기

import openai

client = openai.Client(base_url=f"http://127.0.0.1:{port}/v1", api_key="None")

response = client.chat.completions.create(
    model="qwen/qwen2.5-0.5b-instruct",
    messages=[
        {"role": "user", "content": "List 3 countries and their capitals."},
    ],
    temperature=0,
    max_tokens=64,
)
print(response)

스트리밍 (Streaming)

답변을 조각조각 받고 싶으면 stream=True를 붙이고, 받은 청크를 돌면서 내용을 출력하면 돼요.

import openai

client = openai.Client(base_url=f"http://127.0.0.1:{port}/v1", api_key="None")

# Use stream=True for streaming responses
response = client.chat.completions.create(
    model="qwen/qwen2.5-0.5b-instruct",
    messages=[
        {"role": "user", "content": "List 3 countries and their capitals."},
    ],
    temperature=0,
    max_tokens=64,
    stream=True,
)

# Handle the streaming output
for chunk in response:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)

네이티브 생성 API로 보내기 (Native Generation APIs)

더 유연한 네이티브 /generate 엔드포인트도 있으니 확인해 보세요. 파라미터 참조는 Sampling Parameters에 있어요.

import requests

response = requests.post(
    f"http://localhost:{port}/generate",
    json={
        "text": "The capital of France is",
        "sampling_params": {
            "temperature": 0,
            "max_new_tokens": 32,
        },
    },
)

print(response.json())

스트리밍 (Streaming)

/generate에서도 stream: True를 주면 SSE 형태로 토큰을 조각조각 받을 수 있습니다.

import requests, json

response = requests.post(
    f"http://localhost:{port}/generate",
    json={
        "text": "The capital of France is",
        "sampling_params": {
            "temperature": 0,
            "max_new_tokens": 32,
        },
        "stream": True,
    },
    stream=True,
)

prev = 0
for chunk in response.iter_lines(decode_unicode=False):
    chunk = chunk.decode("utf-8")
    if chunk and chunk.startswith("data:"):
        if chunk == "data: [DONE]":
            break
        data = json.loads(chunk[5:].strip("\n"))
        output = data["text"]
        print(output[prev:], end="", flush=True)
        prev = len(output)
terminate_process(server_process)

더 알아보기 (Learn more)

  • 서버를 올리는 전체 흐름은 Quickstart를 참고해요.
  • 네이티브 /generate가 받는 세부 파라미터는 Sampling Parameters에 정리돼 있어요.