チャットAPIを使ってアプリケーションにジェネレーティブ・チャット機能を追加する
watsonx.ai チャット API を使用して、 基盤モデル使用して回答を生成する会話型ワークフローを構築します。
- 必要な権限
- プロンプトを実行するには、プロジェクト内で管理者または編集者の役割が必要です。
- 必要な認証情報
- watsonx.ai API で認証するには、認証情報を生成する必要があります。 詳細は「 ベアラートークンの生成」 を参照してください。
開発方法
watsonx.ai API で認証するには、認証情報を生成する必要があります。 詳細は「 ベアラートークンの生成」 を参照してください。
これらのプログラミング方法を使用してチャットワークフローを構築することができます:
また、 watsonx.ai UIからグラフィカルツールを使用してチャットワークフローを構築することもできます。 ドキュメントやメディアファイルでのチャットをご覧ください。
概要
watsonx.ai チャットAPIは、会話形式で基盤モデルモデルとやりとりするためのメソッドを実装している。 システムプロンプト、ユーザー入力、 基盤モデル出力(ユーザー固有のフォローアップ質問と回答を含む)など、さまざまなメッセージタイプを識別できます。 チャットAPIを使用して、チャットモードで Prompt Lab、 基盤モデルモデルと対話するときのワークフローを模倣します。
対応基盤モデル
チャットAPIをサポートする基盤モデルリストをプログラムで取得するには、 利用可能な基盤モデルリスト メソッドリクエストを送信する際に、 filters=function_text_chat パラメータを次のように指定します:
curl -X GET \
'https://<region>.<cloud-provider-domain>/ml/v1/foundation_model_specs?version=2024-10-10&filters=function_text_chat'
APIメソッドの詳細については、 watsonx.ai APIリファレンス・ドキュメントを参照のこと。
ツール・コールをサポートする基盤モデル詳細については、 Building agent-driven workflows with chat APIを参照してください。
また、カスタムの基盤モデルチャットワークフローを構築するためにチャットAPIを使用することもできます。 詳細は カスタム・ 基盤モデル推論 を参照。
REST API
チャットAPIは以下のようなタスクに使用できます:
チャットセッションメッセージで使用される role パラメーターは大文字と小文字を区別する。 role は必ず小文字で設定してください。
APIメソッドの詳細については、 watsonx.ai APIリファレンス・ドキュメントを参照のこと。
複数ユーザーによるチャットの例
次のコマンドは、 基盤モデルチャットのリクエストを送信します。
例題のベアラートークンとプロジェクトIDを追加してください。
curl --request POST 'https://<region>.<cloud-provider-domain>/ml/v1/text/chat?version=2024-10-08'
-H 'Authorization: Bearer ${TOKEN}'
-H 'Content-Type: application/json'
-H 'Accept: application/json'
-d '{
"model_id": "meta-llama/llama-3-8b-instruct",
"project_id": "<project ID>",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant that avoids causing harm. When you do not know the answer to a question, you say 'I do not know'."
},
{
"role": "user",
"content": [
{
"type": "text",
"text": "I have a question about Earth. How many moons does the Earth have?"
}
]
},
{
"role": "assistant",
"content": "The Earth has one natural satellite, which is simply called the Moon."
},
{
"role": "user",
"content": [
{
"type": "text",
"text": "What about Saturn?"
}
]
}
],
"max_tokens": 300,
"time_limit": 1000
}'
応答例:
{
"id": "chat-45932923166b4607bde75207a0a9f5d4",
"model_id": "meta-llama/llama-3-8b-instruct",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Saturn has a total of 82 confirmed moons!"
},
"finish_reason": "stop"
}
],
"created": 1728404199,
"created_at": "2024-10-08T16:16:40.102Z",
"usage": {
"completion_tokens": 12,
"prompt_tokens": 87,
"total_tokens": 99
},
"system": {
"warnings": [
{
"message": "This model is a Non-IBM Product governed by a third-party license that may
impose use restrictions and other obligations. By using this model you agree to its terms as
identified in the following URL.",
"id": "disclaimer_warning",
"more_info": "https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/fm-models.html?context=wx"
}
]
}
}
推論機能付きモデルとのチャット例
いくつかの基盤モデル、プロンプトに対する生成された応答とともに、詳細な推論情報を提供する。 次のAPIリクエスト例では、 chat_template_kwargs を使用して、 基盤モデル推論機能を設定し、モデルが出力で提供する詳細の量を制御します。
curl -X POST -kLsS 'https://<region>.<cloud-provider-domain>/ml/v1/text/chat?version=2025-10-25' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer ${TOKEN}" \
-d '{
"stream": false,
"model_id": "openai/gpt-oss-120b",
"project_id": "<project ID>",
"messages": [
{
"role": "user",
"content": "Hi there. What weighs more, a pound of feathers or a kilogram of lead?"
}
],
"chat_template_kwargs": {
"thinking": true
},
"reasoning_effort": "high",
"include_reasoning": true,
"max_completion_tokens": 5000
}'
応答例:
{
"id": "chatcmpl-dc7b2e8ac2854ab79e57738a6e7bad51",
"object": "chat.completion",
"model_id": "openai/gpt-oss-120b",
"model": "openai/gpt-oss-120b",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "The kilogram of lead is heavier.\n\n
**Why?** \n
- **Units:** A pound (lb) and a kilogram (kg) are both units of mass (or weight, depending on the context). On Earth, the conversion is \n\n
\\[\n1\\;\\text{kg} \\approx 2.20462\\;\\text{lb}.\n\\]\n\n
- **Comparison:** \n
- 1 lb ≈ 0.4536 kg \n
- 1 kg ≈ 2.2046 lb \n\n
So the kilogram (≈ 2.2 lb) outweighs the pound (≈ 0.45 kg) by a factor of about 2.2\n\n
---\n\n
### A bit of extra context (just for fun)\n\n
| Property | 1 lb of feathers | 1 kg of lead |\n|----------|------------------|--------------|\n
| **Mass** | 0.4536 kg | 1 kg |\n
| **Weight on Earth** | ≈ 4.44 N (newtons) | ≈ 9.81 N |\n| **Density** | ~0.002–0.003 g / cm³ (very airy) | 11.34 g / cm³ (very dense) |\n
| **Approximate volume** | ~150–200 L (think a small couch‑sized bag) | ~0.09 L (a cube ~4.5 cm on a side) |\n\n
Because feathers are extremely light for their volume, a pound of them would fill a sizable bag, while a kilogram of lead would be a compact, heavy block.\n\n
---\n\n
**Bottom line:** On Earth (or any environment with the same gravity), the kilogram of lead weighs more than a pound of feathers.",
"reasoning_content": "We have a user asking a simple question: \"Hi there. What weights more? A pound of feathers or a kilogram of lead\".
This could be answered with explanation that a kilogram is larger than a pound; 1 kg approx 2.2 pounds,
so kilogram (lead) is heavier. Also clarify differences between weight and mass,
and also the confusion about \"pound\" being a unit of weight in US and the difference between mass and weight.
Might also talk about the volume of feathers vs lead. But the user is asking which weighs more.
So answer: the kilogram of lead weighs more than a pound of feathers, because kilogram is roughly 2.20462 pounds.
However, let's expand to double-check possible nuance: In US version, pound is unit of mass (or weight) and kilogram is metric and we have conversion.
So the answer is kilogram of lead weighs more: about double the weight.
Could also note that weight depends on gravity; but for typical Earth, it's heavier. Also may note that in another gravitational environment it would be different.\n\n
But the user likely expects a quick answer: kilogram of lead is heavier, about 2.2 pounds vs 1 pound.\n\nMake sure to respond politely.\n\n
Potential expansions: question might be a joke, but we can provide explanation.\n\n
Thus answer in clear, concise terms.\n\n
We should stay within appropriate content boundaries. No disallowed content. Good.\n\n
Now produce answer with supportive tone.\n\n
I could also discuss physical densities: feathers take a lot more volume than lead for same mass.
So a pound of feathers would be about a cubic foot (?), whereas a kilogram of lead is a small block.\n\n
Let's compute approximate volumes: density of lead ~ 11.34 g/cm³, so 1 kg = 1000 g → 1000/11.34 ≈ 88.2 cm³ (a cube of ~4.45 cm side).
Feathers: density ~0.0025 g/cm³? Actually down? Let's approximate 0.0025 g/cm³ → 453.592 grams (one pound) /0.0025 ≈ 181,437 cm³ i.e., 0.18 m³ (cube ~0.56 m side).
Actually typical goose feather pack maybe. So huge.\n\n
Potential to talk about \"weight\" vs \"mass\". Provide conversion.\n\n
Ok, will answer."
},
"finish_reason": "stop"
}
],
"created": 1757960415,
"created_at": "2025-09-15T18:20:20.492Z",
"usage": {
"completion_tokens": 868,
"prompt_tokens": 85,
"total_tokens": 953
},
"system": {
"warnings": [
{
"message": "This model is a Non-IBM Product governed by a third-party license that may
impose use restrictions and other obligations. By using this model you agree to its terms as
identified in the following URL.",
"id": "disclaimer_warning",
"more_info": "https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/fm-models.html?context=wx"
}
]
}
}
画像についてのチャットの例
この例では、次の画像が示していることを説明するようモデルに求めている。

サンプルコードは、 Prompt Lab の画像とチャットするのと同じです。 UIを使う別の方法については、 アップロードした画像でチャットをするを参照してください。
チャットAPIから参照する画像の要件は以下の通りです:
- チャットごとに画像を1枚追加
- 対応ファイル形式はPNGまたはJPEGです
- 1枚の画像は、画像サイズによって約1,200~3,000トークンとカウントされる
画像を処理するには、 Base64 としてエンコードする必要があります。 は、画像のバイナリデータを文字列に変換します。 オンラインツールを使って画像を変換するか、コードを使用することができます。
次のサンプル Python、ホストされた画像をエンコードします。 Python notebookからREST APIを呼び出す場合、このコードを使って画像をエンコードすることができる。 そして、POSTリクエストを定義するときに、 image_b64_encoded_string 変数を url 値として指定することができる。
import wget, os, base64
filename = 'downloaded-image.png'
url = 'https://www.ibm.com/able/static/my-input-image.png'
if not os.path.isfile(filename):
wget.download(url, out=filename)
with open(filename, 'rb') as image_file:
image_b64_encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
以下のREST APIリクエストは、 Base64-encoded 文字列で指定された画像についてチャットするためにチャットAPIを使用する。
以下の例では、独自のベアラートークンとプロジェクトIDを追加します。
curl --request POST 'https://<region>.<cloud-provider-domain>/ml/v1/text/chat?version=2024-10-09'
-H 'Authorization: Bearer ${TOKEN}'
-H 'Content-Type: application/json'
-H 'Accept: application/json'
-d '{
"model_id": "meta-llama/llama-3-2-11b-vision-instruct",
"project_id": "<project ID>",
"messages": [
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": "<encoded_string>"
}
},
{
"type": "text",
"text": "What does the image convey about alternative image text?"
}
]
}
],
"max_tokens": 300,
"time_limit": 10000
}'
応答例:
{
"id": "chat-f5f3ab2b8d7f4657b72a4f868e24f3fd",
"model_id": "meta-llama/llama-3-2-90b-vision-instruct",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "The image shows a bar chart on a laptop screen with alternative image text that describes the content of the image.
The alternative image text is \"bar chart showing month's daily sales against historical average.\"
This text provides a clear and concise description of the image, allowing users who cannot see the image to understand its content.\n\n
**Key Points:**\n\n
* The image is a bar chart on a laptop screen.\n
* The alternative image text describes the content of the image.\n
* The alternative image text is \"bar chart showing month's daily sales against historical average.\"\n
* The text provides a clear and concise description of the image.\n\n
**Conclusion:**\n\n
The image conveys that alternative image text should be used to provide a clear and concise description of an image, even if the image
cannot be seen. This is important for accessibility reasons, as it allows users who cannot see the image to still understand its content."
},
"finish_reason": "stop"
}
],
"created": 1728564568,
"model_version": "3.2.0",
"created_at": "2024-10-10T12:49:35.286Z",
"usage": {
"completion_tokens": 184,
"prompt_tokens": 21,
"total_tokens": 205
},
"system": {
"warnings": [
{
"message": "This model is a Non-IBM Product governed by a third-party license that may
impose use restrictions and other obligations. By using this model you agree to its terms as
identified in the following URL.",
"id": "disclaimer_warning",
"more_info": "https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/fm-models.html?context=wx"
}
]
}
}
Python
watsonx.ai Python ライブラリの ModelInference クラスを参照。
まずは、以下のサンプルノートブックをご覧ください:
- REST APIを使用して会話タスクを完了する: watsonx および mistral-medium-2505 を使用して、簡単なチャット会話とツール呼び出しを実行します。
- Python SDKを使って画像についてチャットする: IBM ロゴの説明を生成するために、 watsonx、画像処理のための meta-llama/llama-3-2-11b-vision-instruct モデルを使用する。
granite-3-3-8b-instructモデルとのチャット中に JSON フォーマットのレスポンスを生成するには、 Python SDK を使用します: JSON レスポンスフォーマットでチャット会話を行うには、 watsonx と ibm/granite-3-3-8b-instruct を使用します。- Python SDKを使用して、
granite-3-3-8b-instructモデルとチャットし、以下の方法でモデルの応答を制御します:- モデルは、回答を生成するために使用される推論に関する詳細を提供する。
- モデルは、トピックの内容をそのまま使ったり、モデル自身の言葉で内容を言い換えたりして、トピックを要約する。 詳細については、 watsonx、 ibm/granite-3-3-8b-instruct を使用してコントロール・ロールでチャット会話を行うを参照してください。
チャットAPIのトラブルシューティング
レスポンスがHTMLフォーマットで、 Gateway time-out に言及している場合、リクエストに時間がかかりすぎて有効期限切れなった可能性がある。 リクエストで指定した time_limit フィールドの値を増やす。