> ## 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.

# テキスト生成機能の実装

本ガイドでは、生成の種類、モデルの選択、プロンプトの作成、マルチターン会話の管理など、テキスト生成のさまざまな側面を解説します。

## 生成の種類

非ストリーミング、ストリーミング、非同期の補完など、さまざまな方法でテキストを生成できます。

### シンプルな生成 (非ストリーミング)

SambaNova または OpenAI の Python クライアントを使用して、非ストリーミング方式でテキスト生成を行うには、以下のコードを使用します。

<CodeGroup>
  ```python Python (SambaNova) theme={}
  from sambanova import SambaNova
  client = SambaNova(
      base_url="your-sambanova-base-url",
      api_key="your-sambanova-api-key"
  )
  completion = client.chat.completions.create(
      model="Meta-Llama-3.3-70B-Instruct",
      messages = [
          {"role": "system", "content": "Answer the question in a couple sentences."},
          {"role": "user", "content": "Share a happy story with me"}
      ]
  )
  print(completion.choices[0].message.content)
  ```

  ```python Python (OpenAI) theme={}
  from openai import OpenAI
  client = OpenAI(
      base_url="your-sambanova-base-url",
      api_key="your-sambanova-api-key"
  )
  completion = client.chat.completions.create(
      model="Meta-Llama-3.3-70B-Instruct",
      messages = [
          {"role": "system", "content": "Answer the question in a couple sentences."},
          {"role": "user", "content": "Share a happy story with me"}
      ]
  )
  print(completion.choices[0].message.content)
  ```
</CodeGroup>

### 非同期生成 (非ストリーミング)

非同期の補完には、AsyncSambaNova または AsyncOpenAI Python クライアントを使用します。

<CodeGroup>
  ```python Python (SambaNova) theme={}
  from sambanova import AsyncSambaNova
  import asyncio
  async def main():
      client = AsyncSambaNova(
          base_url="your-sambanova-base-url",
          api_key="your-sambanova-api-key"
      )
      completion = await client.chat.completions.create(
          model="Meta-Llama-3.3-70B-Instruct",
          messages = [
              {"role": "system", "content": "Answer the question in a couple sentences."},
              {"role": "user", "content": "Share a happy story with me"}
          ]
      )
      print(completion.choices[0].message.content)
  asyncio.run(main())
  ```

  ```python Python (OpenAI) theme={}
  from openai import AsyncOpenAI
  import asyncio
  async def main():
      client = AsyncOpenAI(
          base_url="your-sambanova-base-url",
          api_key="your-sambanova-api-key"
      )
      completion = await client.chat.completions.create(
          model="Meta-Llama-3.3-70B-Instruct",
          messages = [
              {"role": "system", "content": "Answer the question in a couple sentences."},
              {"role": "user", "content": "Share a happy story with me"}
          ]
      )
      print(completion.choices[0].message.content)
  asyncio.run(main())
  ```
</CodeGroup>

### ストリーミング応答

リアルタイムのストリーミング補完には、SambaNova または OpenAI クライアントで以下の方法を使用します。

<CodeGroup>
  ```python Python (SambaNova) theme={}
  from sambanova import SambaNova
  client = SambaNova(
      base_url="your-sambanova-base-url",
      api_key="your-sambanova-api-key"
  )
  completion = client.chat.completions.create(
      model="Meta-Llama-3.3-70B-Instruct",
      messages = [
          {"role": "system", "content": "Answer the question in a couple sentences."},
          {"role": "user", "content": "Share a happy story with me"}
      ],
      stream = True
  )
  for chunk in completion:
    print(chunk.choices[0].delta.content, end="")
  ```

  ```python Python (OpenAI) theme={}
  from openai import OpenAI
  client = OpenAI(
      base_url="your-sambanova-base-url",
      api_key="your-sambanova-api-key"
  )
  completion = client.chat.completions.create(
      model="Meta-Llama-3.3-70B-Instruct",
      messages = [
          {"role": "system", "content": "Answer the question in a couple sentences."},
          {"role": "user", "content": "Share a happy story with me"}
      ],
      stream = True
  )
  for chunk in completion:
    print(chunk.choices[0].delta.content, end="")
  ```
</CodeGroup>

## 複数の補完

`n` パラメータを使用すると、単一のプロンプトに対して複数の独立した補完を生成できます。レスポンスの `choices[0]` から `choices[n-1]` に、それぞれの補完が含まれます。

| パラメータ | 型 | デフォルト値 | 有効範囲 |
| :- | :- | :- | :- |
| `n` | integer | 1 | 1–8 |

<Note>
  補完ごとに異なる出力を得るには、`temperature` を 0 より大きい値に設定してください。`temperature: 0` の場合、すべての補完が同一になります。
</Note>

<Warning>
  Function calling (関数呼び出し) やツールの利用時には、1 より大きい `n` は未対応です。組み合わせると 400 エラーが返されます。
</Warning>

<CodeGroup>
  ```python Python (SambaNova) theme={}
  from sambanova import SambaNova

  client = SambaNova(
      base_url="your-sambanova-base-url",
      api_key="your-sambanova-api-key"
  )

  completion = client.chat.completions.create(
      model="Meta-Llama-3.1-8B-Instruct",
      messages=[
          {"role": "user", "content": "Write a one-sentence tagline for a coffee shop."}
      ],
      n=3,
      temperature=0.7
  )

  for i, choice in enumerate(completion.choices):
      print(f"Completion {i + 1}: {choice.message.content}")
  ```

  ```python Python (OpenAI) theme={}
  from openai import OpenAI

  client = OpenAI(
      base_url="your-sambanova-base-url",
      api_key="your-sambanova-api-key"
  )

  completion = client.chat.completions.create(
      model="Meta-Llama-3.1-8B-Instruct",
      messages=[
          {"role": "user", "content": "Write a one-sentence tagline for a coffee shop."}
      ],
      n=3,
      temperature=0.7
  )

  for i, choice in enumerate(completion.choices):
      print(f"Completion {i + 1}: {choice.message.content}")
  ```
</CodeGroup>

これは、SambaCloud と SambaStack の両方に当てはまります。

## モデルの選択

モデルはアーキテクチャがそれぞれ異なり、速度や応答品質に影響します。モデルの選択は、以下に示す要素によって決まります。

| **要素** | **考慮事項** |
| :- | :- |
| タスクの複雑さ | 複雑なタスクには、より大きなモデルが適しています。 |
| 精度要件 | 一般に、より大きなモデルほど高い精度が得られます。 |
| 費用とリソース | より大きなモデルは、費用が増え、必要なリソースも多くなります。 |

さまざまなモデルを試して、ご自身のユースケースに最も適したモデルを見つけてください。

## 効果的なプロンプトの作成

プロンプトエンジニアリングとは、LLM からの応答を最適化するためにプロンプトを設計・改良する手法です。このプロセスは反復的であり、最良の結果を得るには試行錯誤が必要です。

### プロンプトの構築

基本的なプロンプトは、LLM から応答を引き出すためのわずか数語で十分な場合もあります。ただし、より複雑なユースケースでは、以下のような追加の要素が必要になることがあります。

| **要素** | **説明** |
| :- | :- |
| ペルソナの定義 | モデルに特定の役割を割り当てます (例: "You are a financial advisor")。 |
| コンテキストの提供 | モデルの応答を導くための背景情報を与えます。 |
| 出力形式の指定 | 特定のスタイル (例: JSON、箇条書き、構造化テキスト) で応答するようモデルに指示します。 |
| ユースケースの記述 | 対話の目的を明確にします。 |

### 高度なプロンプト手法

応答品質と reasoning を向上させるために、より高度な手法を使用できます。

| **手法** | **説明** |
| :- | :- |
| In-context learning (文脈内学習) | 望ましい出力の例を提供してモデルを導きます。 |
| 「思考の連鎖」(Chain-of-Thought; CoT) プロンプティング | 応答を返す前に、reasoning の過程を明示するようモデルを促します。 |

プロンプトエンジニアリングの詳細については、[A Systematic Survey of Prompt Engineering in Large Language Models: Techniques and Applications](https://arxiv.org/pdf/2402.07927)（英語）をご参照ください。

### メッセージとロール

チャットベースの対話では、メッセージは特定のロールとコンテンツを持つ辞書として表現されます。

| **要素** | **説明** |
| :- | :- |
| `role` | メッセージの送信者を指定します。 |
| `content` | メッセージのテキストを含みます。 |

#### 主なロール

ロールは通常、`system`、`user`、`assistant` に分類されます。

| **ロール** | **説明** |
| :- | :- |
| `system` | モデルへの全般的な指示を与えます。 |
| `user` | ユーザーの入力を表します。 |
| `assistant` | モデルの応答を含みます。 |
| `tool` | ツールの実行結果を含みます。 |

## マルチターン会話

複数のやり取りにわたってコンテキストを維持するために、会話型 AI システムのメッセージは通常、辞書のリストとして保存されます。各辞書には、送信者のロールとメッセージ内容を指定するキーが含まれます。この構造により、システムは会話の複数ターンにわたってコンテキストを追跡できます。

以下は、**Meta-Llama-3.3-70B-Instruct** モデルを使用したマルチターン会話の構成例です。

```python Structuring multi-turn conversations using Meta-Llama-3.3-70B-Instruct theme={}
completion = client.chat.completions.create(
    model="Meta-Llama-3.3-70B-Instruct",
    messages = [
        {"role": "user", "content": "Hi! My name is Peter and I am 31 years old. What is 1+1?"},
        {"role": "assistant", "content": "Nice to meet you, Peter. 1 + 1 is equal to 2"},
        {"role": "user", "content": "What is my age?"}
    ],
    stream = True
)
for chunk in completion:
  print(chunk.choices[0].delta.content, end="")
```

プログラムを実行すると、以下のような出力が表示されます。

```python Example output theme={}
You told me earlier, Peter. You're 31 years old.
```

このように会話を構成することで、モデルはコンテキストを維持し、過去のユーザー入力を想起し、より一貫性のある応答を返すことができます。

### 長い会話における考慮事項

LLM と長い会話を行う場合、正確さと一貫性を確保するために、トークン制限やメモリ制約といった要素を考慮する必要があります。

* **トークン制限** - LLM には固定のコンテキストウィンドウがあり、1 回のリクエストで処理できるトークン数に制限があります。入力がこの制限を超えると、システムによって切り詰められ、不完全または一貫性を欠いた応答につながる可能性があります。
* **メモリ制約** - モデルは、入力ウィンドウを超えてコンテキストを保持しません。コンテキストを維持するには、過去のメッセージをプロンプトに再度含める必要があります。

プロンプトを効果的に構成し、会話履歴を適切に管理することで、LLM とのやり取りを最適化し、より高い正確さと一貫性を実現できます。

## DeepSeek-V3.2 の思考モード

DeepSeek-V3.2 は、オプションの思考モード (thinking mode) に対応しており、最終応答と並んで、独立した `reasoning` フィールドにモデルの reasoning を出力します。思考モードはデフォルトで無効です。有効にするには、リクエストで `chat_template_kwargs` に `enable_thinking` を `true` として渡します。

<Note>
  思考モードは、DeepSeek-V3.2 の連続バッチング (continuous batching; CB) バンドルのデプロイメントで利用できます。お使いの環境で利用可能なバンドルについては、SambaNova 管理者にお問い合わせください。
</Note>

```bash curl theme={}
curl -X POST https://your-sambastack-url/v1/chat/completions \
  -H "Authorization: Bearer your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "DeepSeek-V3.2",
    "messages": [
      {"role": "system", "content": "You are a helpful assistant"},
      {"role": "user", "content": "Explain how photosynthesis works."}
    ],
    "chat_template_kwargs": {"enable_thinking": true}
  }'
```

思考モードを有効にすると、応答にはモデルの思考の連鎖を含む `reasoning` フィールドが含まれます。最終回答は `content` に表示されます。

## Gemma 4 31B の思考モード

Gemma 4 31B (`gemma-4-31B-it`) は、オプションの思考モードに対応しており、最終応答と並んで、独立した `reasoning` フィールドにモデルの reasoning を出力します。思考モードはデフォルトで無効です。有効にするには、リクエストで `chat_template_kwargs` に `enable_thinking` を `true` として渡します。

Gemma 4 31B は、思考モードと併用できるツール呼び出しに対応しています。両方が有効な場合、モデルは問題について reasoning を行い、同じ応答内でツール呼び出しの判断を返します。

<Note>
  思考モードは、すべての `gemma-4-31b-32-128k` バンドルのデプロイメントで利用できます。
</Note>

<Warning>
  `reasoning` フィールドは会話履歴には戻されません。マルチターン会話では、モデルは自身の過去の reasoning にアクセスできません。以降のターンで過去の reasoning が利用できることを前提にしないでください。
</Warning>

```bash curl theme={}
curl -X POST https://your-sambastack-url/v1/chat/completions \
  -H "Authorization: Bearer your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemma-4-31B-it",
    "messages": [
      {"role": "system", "content": "You are a helpful assistant"},
      {"role": "user", "content": "Compare the trade-offs between using a relational database and a document store for a high-write e-commerce workload."}
    ],
    "chat_template_kwargs": {"enable_thinking": true}
  }'
```

思考モードを有効にすると、応答にはモデルの思考の連鎖を含む `reasoning` フィールドが含まれます。最終回答は `content` に表示されます。ツール呼び出しも有効な場合、`content` は `null` になり、モデルの判断は `reasoning` と並んで `tool_calls` に表示されます。

**応答例 (ツール呼び出しを伴う思考モード)**

```json theme={}
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": null,
        "reasoning": "The user wants me to call a tool to get the integer 7. Looking at the available tools, there is a function called `return_integer` which takes an integer `value` as a parameter. I should call `return_integer` with `value=7`.",
        "role": "assistant",
        "tool_calls": [
          {
            "function": {
              "arguments": "{\"value\":7}",
              "name": "return_integer"
            },
            "id": "call_92ad8c74a4594172b6",
            "type": "function"
          }
        ]
      }
    }
  ],
  "id": "42d3a6ac-d984-40b1-9389-f5af73cb599e",
  "model": "gemma-4-31B-it",
  "object": "chat.completion",
  "usage": {
    "completion_tokens": 74,
    "prompt_tokens": 91,
    "total_tokens": 165
  }
}
```
