> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sambanova.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# vLLM

[vLLM](https://docs.vllm.ai/) は、LLM のためのオープンソースの推論・サービングエンジンです。vLLM は OpenAI 互換の API を提供するため、セルフホストの vLLM サーバー向けに `openai` Python クライアントで書いたコードは、ベース URL、API キー、モデルを変更するだけで SambaCloud に対して実行できます。本ページでは、その変更内容と、あわせて調整が必要な点を説明します。

## 前提条件

* [SambaCloud](https://cloud.sambanova.ai/?utm_source=vllm\&utm_medium=external\&utm_campaign=cloud_signup) のアカウントと [API キー](https://cloud.sambanova.ai/apis?utm_source=vllm\&utm_medium=external\&utm_campaign=cloud_signup)
* Python 3.10 以上と `openai` パッケージ (`pip install openai`)

## OpenAI クライアントの接続先を SambaCloud に変更

vLLM 自身のドキュメントでは、セルフホストしたサーバーへの問い合わせを次のように示しています。

```python vllm_local.py theme={}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="token-abc123",
)

completion = client.chat.completions.create(
    model="NousResearch/Meta-Llama-3-8B-Instruct",
    messages=[{"role": "user", "content": "Hello!"}],
)
print(completion.choices[0].message)
```

接続先を SambaCloud に切り替える場合、主な変更点は `base_url`、`api_key`、`model` の 3 つです。

```python sambanova_swap.py theme={}
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.sambanova.ai/v1",
    api_key=os.environ["SAMBANOVA_API_KEY"],
)

completion = client.chat.completions.create(
    model="MiniMax-M3.1-Flash",
    messages=[{"role": "user", "content": "What can you do?"}],
)
print(completion.choices[0].message.content)
```

```text Output (abridged) theme={}
I can help you think, write, learn, and solve problems. For example:

- **Answer questions** and explain complex topics in simple terms
- **Write and edit** emails, essays, stories, résumés, and reports
- **Write or debug code** and explain how software works
...
```

## vLLM 固有のパラメータ

vLLM の OpenAI 互換サーバーは、`top_k` のように標準の OpenAI API にはないパラメータをいくつかサポートしており、クライアントの `extra_body` 引数を通じて渡します。

```python theme={}
completion = client.chat.completions.create(
    model="MiniMax-M3.1-Flash",
    messages=[{"role": "user", "content": "What can you do?"}],
    extra_body={"top_k": 20},
)
```

> [!NOTE]
>
> SambaCloud は、vLLM と同じように `extra_body` 経由の `top_k` を受け付けます。SambaCloud が対応するその他のパラメータについては、[OpenAI 互換性](https://docs.sambanova.ai/docs/ja/features/openai-compatibility.md) をご参照ください。

## ツール呼び出し

vLLM の [ツール呼び出しの例](https://github.com/vllm-project/vllm/blob/main/examples/tool_calling/openai_chat_completion_client_with_tools.py) は、ストリーミングを含めて標準の `tools` 引数を使用しています。非ストリーミングの呼び出しは、同じ `tools` 引数のまま SambaCloud でも動作します。ストリーミングのループには、下の警告で説明するガードが 1 つ必要です。

```python theme={}
tools = [{
    "type": "function",
    "function": {
        "name": "get_current_weather",
        "description": "Get the current weather in a given location",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {"type": "string"},
                "state": {"type": "string"},
                "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
            },
            "required": ["city", "state", "unit"],
        },
    },
}]

completion = client.chat.completions.create(
    model="MiniMax-M3.1-Flash",
    messages=[{"role": "user", "content": "What's the temperature in Dallas, in fahrenheit?"}],
    tools=tools,  # same OpenAI "function" tool schema vLLM's example uses
)
print(completion.choices[0].message.tool_calls)
```

```text Output theme={}
[ChatCompletionMessageFunctionToolCall(id='call_4255df7f20184da18e', function=Function(arguments='{"city": "Dallas", "state": "TX", "unit": "fahrenheit"}', name='get_current_weather'), type='function')]
```

> [!WARNING]
>
> SambaCloud からのストリーミング応答は、必ず `choices` リストが空の最終チャンクで終わります (このチャンクは `usage` の統計情報のみを運びます)。vLLM 自身のストリーミング例は `chunk.choices[0]` を無条件に参照するため、この最終チャンクで `IndexError` が発生します。`chunk.choices[0].delta` を読む前に、`if not chunk.choices: continue` でガードしてください。

## 構造化出力 (JSON スキーマ)

vLLM の [構造化出力の例](https://docs.vllm.ai/en/latest/features/structured_outputs.html) は、`json_schema` を指定した `response_format` を使用しています。SambaCloud も同じ `response_format` を受け付けます。

```python theme={}
from pydantic import BaseModel

class CarDescription(BaseModel):
    brand: str
    model: str
    car_type: str

completion = client.chat.completions.create(
    model="MiniMax-M3.1-Flash",
    messages=[{"role": "user", "content": "Generate a JSON with the brand, model and car_type of the most iconic car from the 90's"}],
    response_format={
        "type": "json_schema",
        "json_schema": {"name": "car-description", "schema": CarDescription.model_json_schema()},
    },
)
print(completion.choices[0].message.content)
```

```text Output theme={}
{
  "brand": "Toyota",
  "car_type": "Sports car",
  "model": "Supra Mk4 (A80)"
}
```

## トラブルシューティング

> [accordion] KeyError: SAMBANOVA\_API\_KEY
>
> 実行前にキーをエクスポートしてください: `export SAMBANOVA_API_KEY="your-key"`。`echo $SAMBANOVA_API_KEY` で確認できます。

> [accordion] Model not found
>
> `NousResearch/Meta-Llama-3-8B-Instruct` のような vLLM のモデル名は Hugging Face のリポジトリパスであり、そのままでは使えません。代わりに SambaCloud のモデル ID を使用してください。現在の一覧は [SambaCloud モデル](https://docs.sambanova.ai/docs/ja/models/sambacloud-models.md) をご参照ください。

> [accordion] IndexError: list index out of range while streaming
>
> ストリーミング応答の最終チャンクは、`choices` リストが空です (トークン使用量のみを運びます)。上の [ツール呼び出し](#ツール呼び出し) で説明したとおり、`chunk.choices[0]` を参照する前に、choices が空のチャンクをスキップしてください。

## 参考情報

* [vLLM ドキュメント](https://docs.vllm.ai/)
* [vLLM の OpenAI 互換サーバー](https://docs.vllm.ai/en/latest/serving/online_serving/openai_compatible_server.html)
* [vLLM のサンプル集](https://docs.vllm.ai/en/latest/examples/)
* [vLLM のツール呼び出しの例](https://github.com/vllm-project/vllm/blob/main/examples/tool_calling/openai_chat_completion_client_with_tools.py)
* [vLLM の構造化出力](https://docs.vllm.ai/en/latest/features/structured_outputs.html)
* [SambaCloud の対応モデル](https://docs.sambanova.ai/docs/ja/models/sambacloud-models.md)
