テキストモデル
メッセージを作成する
CometAPI の Messages エンドポイントを通じて Claude を呼び出し、テキストと画像の入力、適応的思考、プロンプトキャッシュ、ストリーミング(Streaming)、ツールを使用します。
POST
/
v1
/
messages
import os
import anthropic
client = anthropic.Anthropic(
base_url="https://api.cometapi.com",
api_key=os.environ["COMETAPI_KEY"],
)
message = client.messages.create(
model="claude-opus-5",
max_tokens=1000,
messages=[
{
"role": "user",
"content": "Suggest three search queries about renewable energy storage.",
},
],
)
for block in message.content:
if block.type == "text":
print(block.text)
{
"id": "msg_example",
"type": "message",
"role": "assistant",
"model": "claude-opus-5",
"content": [
{
"type": "text",
"text": "Here are three search queries covering different angles of the topic:\n\n1. **\"grid-scale battery storage cost trends 2024 2025\"**\n — Targets economics and recent price data for lithium-ion and other utility-scale systems.\n\n2. **\"long-duration energy storage technologies comparison flow battery vs compressed air vs thermal\"**\n — Surfaces technical comparisons of options for storage beyond the 4–8 hour range, where lithium-ion becomes less cost-effective.\n\n3. **\"green hydrogen seasonal storage feasibility round-trip efficiency\"**\n — Digs into the viability of hydrogen for multi-week or seasonal balancing, including its efficiency penalties.\n\n**A few tips for refining these:**\n- Add `site:.gov` or `site:.edu` to prioritize research and agency reports (e.g., NREL, IEA, DOE).\n- Append a region like `Europe`, `India`, or `California` if you need location-specific policy or deployment data.\n- Try `filetype:pdf` to pull up technical white papers and government studies directly.\n\nWant me to tailor these toward a specific use case — academic research, investment analysis, or policy work?"
}
],
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 23,
"cache_creation_input_tokens": 0,
"cache_read_input_tokens": 0,
"cache_creation": {
"ephemeral_5m_input_tokens": 0,
"ephemeral_1h_input_tokens": 0
},
"output_tokens": 437,
"output_tokens_details": {
"thinking_tokens": 50
}
}
}POST /v1/messages を使用して、Anthropic メッセージ形式で Claude にリクエストを送信します。
これらの例では、公式の Anthropic SDK に CometAPI のベース URL を設定し、
$COMETAPI_KEY から API キーを読み取ります。
フィールドの定義とモデル固有のオプションについては、次の公式資料を参照してください:
Messages API リファレンス.
OpenAI 互換のリクエストについては、次を参照してください: チャット補完.
x-api-key または Authorization: Bearer を使用して認証します。Anthropic SDK が使用するのは
x-api-keyです。HTTP の例には anthropic-version: 2023-06-01 が含まれます。クイックスタート
次の例では、3 つの検索クエリを要求します。$COMETAPI_KEY を設定してから
実行してください。Python の場合は anthropic を、JavaScript の場合は @anthropic-ai/sdk をインストールします:
curl "https://api.cometapi.com/v1/messages" \
-H "Content-Type: application/json" \
-H "x-api-key: $COMETAPI_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-opus-5",
"max_tokens": 1000,
"messages": [
{
"role": "user",
"content": "Suggest three search queries about renewable energy storage."
}
]
}'
import os
import anthropic
client = anthropic.Anthropic(
base_url="https://api.cometapi.com",
api_key=os.environ["COMETAPI_KEY"],
)
message = client.messages.create(
model="claude-opus-5",
max_tokens=1000,
messages=[
{
"role": "user",
"content": "Suggest three search queries about renewable energy storage.",
},
],
)
for block in message.content:
if block.type == "text":
print(block.text)
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic({
apiKey: process.env.COMETAPI_KEY,
baseURL: "https://api.cometapi.com",
});
const message = await client.messages.create({
"model": "claude-opus-5",
"max_tokens": 1000,
"messages": [
{
"role": "user",
"content": "Suggest three search queries about renewable energy storage."
}
]
});
for (const block of message.content) {
if (block.type === "text") console.log(block.text);
}
content 配列が含まれます。type が text であるブロックを読み取ってください。
テキストの前に思考ブロックやツールブロックが現れることがあります。
適応的思考を制御する
thinking.type を adaptive に設定し、output_config.effort の値を選択します。
次の例では xhigh を使用し、ストリームから完了したメッセージを読み取ります:
import os
import anthropic
client = anthropic.Anthropic(
base_url="https://api.cometapi.com",
api_key=os.environ["COMETAPI_KEY"],
)
with client.messages.stream(
model="claude-opus-5",
max_tokens=4096,
messages=[
{
"role": "user",
"content": "A shop sells notebooks for $7 each. Buying three earns a $4 discount. A customer pays $20 for three notebooks. Calculate the total and the change, and explain your steps.",
},
],
thinking={
"type": "adaptive",
},
output_config={
"effort": "xhigh",
},
) as stream:
message = stream.get_final_message()
for block in message.content:
if block.type == "text":
print(block.text)
max_tokens の出力上限に含まれます。最終的な
回答と思考の両方に十分な余裕を確保してください。レスポンスにテキストが含まれていても、
思考ブロックが表示されないことがあります。返された思考ブロックはすべて、会話
履歴に変更せずに保持してください。
モデル固有の思考設定については、次を参照してください:
思考.
これらの例では temperature、top_p、top_k を省略しています。サンプリング制御を追加する前に、選択した
モデルのパラメータに関するドキュメントを確認してください。
プロンプトをキャッシュする
リクエスト間で再利用する参照資料にキャッシュのブレークポイントを設定します。 実行する前に、参照資料を UTF-8 のreference.txt ファイルに保存してください。この
例では、選択したモデルの次の条件を満たすプレフィックスを使用してください:
キャッシュ可能な最小長:
import os
from pathlib import Path
import anthropic
client = anthropic.Anthropic(
base_url="https://api.cometapi.com",
api_key=os.environ["COMETAPI_KEY"],
)
reference = Path("reference.txt").read_text(encoding="utf-8")
with client.messages.stream(
model="claude-sonnet-5",
max_tokens=1024,
messages=[
{
"role": "user",
"content": "How long can customers return damaged books, and what must they provide?",
},
],
system=[
{
"type": "text",
"text": reference,
"cache_control": {
"type": "ephemeral",
},
},
],
) as stream:
message = stream.get_final_message()
for block in message.content:
if block.type == "text":
print(block.text)
print(message.usage.model_dump_json())
cache_creation_input_tokensはキャッシュに書き込まれたトークン(Token)をカウントします。cache_read_input_tokensはキャッシュから読み取られたトークン(Token)をカウントします。input_tokensはこれらのキャッシュカウンターの対象外で処理された入力をカウントします。
cache_read_input_tokens が入力トークン(Token)のうち
キャッシュから読み取られた数を示します。OpenAPI の プロンプト(Prompt)キャッシュ
の例には、次の名前で保存できる完全な架空の参照資料が含まれています:
reference.txt 。サンプルを試す際に使用できます。
レスポンスをストリーミングする
Server-Sent Events を使用するにはstream: true を設定します。SDK はテキストの断片を
到着するたびに公開します:
import os
import anthropic
client = anthropic.Anthropic(
base_url="https://api.cometapi.com",
api_key=os.environ["COMETAPI_KEY"],
)
with client.messages.stream(
model="claude-opus-5",
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Write a two-line poem about a comet.",
},
],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
message_start、コンテンツブロックイベント、message_delta、
および message_stop が含まれます。コンテンツブロックには、テキスト、思考、ツールの動作が含まれることがあります。
テキストブロックでは、content_block_delta に text_delta が含まれます。最終的な使用量
と停止理由は message_delta から読み取ります。
推論量を制御する
output_config.effort を設定して推論量を調整します。この例では
low を使って短い説明を求め、ストリーミングされたメッセージの完了を待ちます:
import os
import anthropic
client = anthropic.Anthropic(
base_url="https://api.cometapi.com",
api_key=os.environ["COMETAPI_KEY"],
)
with client.messages.stream(
model="claude-opus-5",
max_tokens=1000,
messages=[
{
"role": "user",
"content": "Summarize the benefit of automated tests in one sentence.",
},
],
output_config={
"effort": "low",
},
) as stream:
message = stream.get_final_message()
for block in message.content:
if block.type == "text":
print(block.text)
max_tokens を別途設定します。
サーバーツールを使用する
サーバーツールは API リクエスト中に実行され、 Claude の回答とともに結果ブロックを返します。- Web 取得
- Web 検索
論文を取得し、取得したドキュメントを回答に使用するよう Claude に依頼します。
この例ではレスポンスをストリーミングし、最終テキストと
レスポンスでは
web_fetch_tool_result ブロックの両方を確認します:import os
import anthropic
client = anthropic.Anthropic(
base_url="https://api.cometapi.com",
api_key=os.environ["COMETAPI_KEY"],
)
with client.messages.stream(
model="claude-sonnet-5",
max_tokens=2048,
messages=[
{
"role": "user",
"content": "Fetch https://arxiv.org/abs/1512.03385 and state the paper title and the proposed learning framework in two sentences.",
},
],
tools=[
{
"type": "web_fetch_20250910",
"name": "web_fetch",
"max_uses": 3,
},
],
) as stream:
message = stream.get_final_message()
for block in message.content:
if block.type == "text":
print(block.text)
for block in message.content:
if block.type == "web_fetch_tool_result":
print(block.model_dump_json())
server_tool_use ブロックと web_fetch_tool_result が対応しており、
後者には取得したドキュメントまたはツールエラーが含まれます。公式のリリース日を検索し、出典を引用するよう Claude に依頼します。
この例ではレスポンスをストリーミングし、最終メッセージを収集して、
返された検索結果の出典を出力します:レスポンスでは
import os
import anthropic
client = anthropic.Anthropic(
base_url="https://api.cometapi.com",
api_key=os.environ["COMETAPI_KEY"],
)
with client.messages.stream(
model="claude-sonnet-5",
max_tokens=4096,
messages=[
{
"role": "user",
"content": "Search the web for the official Python 3.14 release date. Answer with the date and cite a source.",
},
],
tools=[
{
"type": "web_search_20250305",
"name": "web_search",
"max_uses": 3,
},
],
) as stream:
message = stream.get_final_message()
for block in message.content:
if block.type == "text":
print(block.text)
for block in message.content:
if block.type == "web_search_tool_result":
if isinstance(block.content, list):
for result in block.content:
if result.type == "web_search_result":
print(result.title, result.url)
server_tool_use ブロックと web_search_tool_result が対応しており、
後者には出典が含まれます。この結果ブロックから出典のタイトルと URL を読み取ります。クライアントツールの結果を返す
クライアントツールの場合、Claude はtool_use ブロックを返します。アプリケーションの関数を実行し、
その結果を、対応する tool_result ブロックに tool_use_id を指定して送信します。
2 つのリクエストの間で assistant のコンテンツをすべて保持してください。
次の例では、架空の注文結果を渡し、その結果を使用するよう Claude に依頼します:
import json
import os
import anthropic
client = anthropic.Anthropic(
base_url="https://api.cometapi.com",
api_key=os.environ["COMETAPI_KEY"],
)
tools = [{
"name": "get_order_status",
"description": "Look up the status of a demonstration order.",
"input_schema": {
"type": "object",
"properties": {
"order_id": {
"type": "string",
"description": "The order reference.",
},
},
"required": ["order_id"],
},
}]
messages = [{
"role": "user",
"content": "Check the status of demo-order-42 using the order tool.",
}]
with client.messages.stream(
model="claude-opus-5",
max_tokens=1000,
messages=messages,
tools=tools,
) as stream:
message = stream.get_final_message()
tool_call = next(b for b in message.content if b.type == "tool_use")
messages.append({
"role": "assistant",
"content": [block.model_dump() for block in message.content],
})
messages.append({
"role": "user",
"content": [{
"type": "tool_result",
"tool_use_id": tool_call.id,
"content": json.dumps({
"status": "ready_for_pickup",
"pickup_code": "COMET42",
}),
}],
})
with client.messages.stream(
model="claude-opus-5",
max_tokens=1000,
messages=messages,
tools=tools,
) as stream:
follow_up = stream.get_final_message()
for block in follow_up.content:
if block.type == "text":
print(block.text)
レスポンスの例
ストリーミング(Streaming)を使用しないリクエストはメッセージオブジェクトを返します。次の例では、 テキストと使用量のフィールドを、例示用のメッセージ識別子とともに示します:{
"id": "msg_example",
"type": "message",
"role": "assistant",
"model": "claude-opus-5",
"content": [
{
"type": "text",
"text": "Here are three search queries covering different angles of the topic:\n\n1. **\"grid-scale battery storage cost trends 2024 2025\"**\n — Targets economics and recent price data for lithium-ion and other utility-scale systems.\n\n2. **\"long-duration energy storage technologies comparison flow battery vs compressed air vs thermal\"**\n — Surfaces technical comparisons of options for storage beyond the 4–8 hour range, where lithium-ion becomes less cost-effective.\n\n3. **\"green hydrogen seasonal storage feasibility round-trip efficiency\"**\n — Digs into the viability of hydrogen for multi-week or seasonal balancing, including its efficiency penalties.\n\n**A few tips for refining these:**\n- Add `site:.gov` or `site:.edu` to prioritize research and agency reports (e.g., NREL, IEA, DOE).\n- Append a region like `Europe`, `India`, or `California` if you need location-specific policy or deployment data.\n- Try `filetype:pdf` to pull up technical white papers and government studies directly.\n\nWant me to tailor these toward a specific use case — academic research, investment analysis, or policy work?"
}
],
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 23,
"cache_creation_input_tokens": 0,
"cache_read_input_tokens": 0,
"cache_creation": {
"ephemeral_5m_input_tokens": 0,
"ephemeral_1h_input_tokens": 0
},
"output_tokens": 437,
"output_tokens_details": {
"thinking_tokens": 50
}
}
}
end_turn は回答の完了を示し、
max_tokens は出力が上限に達したことを示し、tool_use はクライアントツールの
結果を要求します。pause_turn を返すサーバーツールのターンでは、
返された assistant のコンテンツを変更せずに続行します。承認
ヘッダー
ボディ
application/json
レスポンス
Successful response. When stream is true, the response is a stream of SSE events.
最終更新日 2026年11月14日
⌘I
import os
import anthropic
client = anthropic.Anthropic(
base_url="https://api.cometapi.com",
api_key=os.environ["COMETAPI_KEY"],
)
message = client.messages.create(
model="claude-opus-5",
max_tokens=1000,
messages=[
{
"role": "user",
"content": "Suggest three search queries about renewable energy storage.",
},
],
)
for block in message.content:
if block.type == "text":
print(block.text)
{
"id": "msg_example",
"type": "message",
"role": "assistant",
"model": "claude-opus-5",
"content": [
{
"type": "text",
"text": "Here are three search queries covering different angles of the topic:\n\n1. **\"grid-scale battery storage cost trends 2024 2025\"**\n — Targets economics and recent price data for lithium-ion and other utility-scale systems.\n\n2. **\"long-duration energy storage technologies comparison flow battery vs compressed air vs thermal\"**\n — Surfaces technical comparisons of options for storage beyond the 4–8 hour range, where lithium-ion becomes less cost-effective.\n\n3. **\"green hydrogen seasonal storage feasibility round-trip efficiency\"**\n — Digs into the viability of hydrogen for multi-week or seasonal balancing, including its efficiency penalties.\n\n**A few tips for refining these:**\n- Add `site:.gov` or `site:.edu` to prioritize research and agency reports (e.g., NREL, IEA, DOE).\n- Append a region like `Europe`, `India`, or `California` if you need location-specific policy or deployment data.\n- Try `filetype:pdf` to pull up technical white papers and government studies directly.\n\nWant me to tailor these toward a specific use case — academic research, investment analysis, or policy work?"
}
],
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 23,
"cache_creation_input_tokens": 0,
"cache_read_input_tokens": 0,
"cache_creation": {
"ephemeral_5m_input_tokens": 0,
"ephemeral_1h_input_tokens": 0
},
"output_tokens": 437,
"output_tokens_details": {
"thinking_tokens": 50
}
}
}