Metin Modelleri
Mesaj oluşturma
Claude’u metin ve görüntü girdisi, uyarlanabilir düşünme, prompt önbelleğe alma, Streaming ve araçlarla CometAPI Messages uç noktası üzerinden çağırın.
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 kullanarak Claude isteklerini Anthropic Messages formatında gönderin.
Örnekler, resmi Anthropic SDK’yi CometAPI temel URL’siyle yapılandırır ve
API anahtarınızı $COMETAPI_KEY üzerinden okur.
Alan tanımları ve modele özgü seçenekler için resmi
Messages API referansına bakın.
OpenAI uyumlu istekler için bkz. Chat Completions.
x-api-key veya Authorization: Bearer ile kimlik doğrulaması yapın. Anthropic SDK şu anahtarı kullanır:
x-api-key. HTTP örnekleri anthropic-version: 2023-06-01 içerir.Hızlı başlangıç
Aşağıdaki örnekler üç arama sorgusu ister.$COMETAPI_KEY değerini ayarlayın, ardından
bunları çalıştırın. Python için anthropic veya JavaScript için @anthropic-ai/sdk yükleyin:
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 dizisi içerir. type değeri text olan blokları okuyun;
düşünme ve araç blokları metinden önce görünebilir.
Uyarlanabilir düşünmeyi denetleme
thinking.type değerini adaptive olarak ayarlayın ve bir output_config.effort değeri seçin.
Aşağıdaki örnek xhigh kullanır ve tamamlanan iletiyi bir akıştan okur:
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 çıktı sınırına katkıda bulunur. Nihai
yanıtın yanı sıra düşünme için de yer bırakın. Bir yanıt, görünür bir
düşünme bloğu olmadan metin içerebilir. Döndürülen tüm düşünme bloklarını sohbet
geçmişinde değiştirmeden koruyun.
Modele özgü düşünme yapılandırması için
Düşünme bölümüne bakın..
Örneklerde temperature, top_p ve top_k kullanılmamıştır; örnekleme denetimleri eklemeden önce seçilen
modelin parametre belgelerine başvurun.
Prompt’ları önbelleğe alma
İstekler arasında yeniden kullandığınız referans materyaline bir önbellek kesme noktası yerleştirin. Referans materyalinizi UTF-8reference.txt dosyasına bu
örneği çalıştırmadan önce kaydedin. Seçilen modelin
önbelleğe alınabilir minimum uzunluğunu karşılayan bir önek kullanın.:
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önbelleğe yazılan token’ları sayar.cache_read_input_tokensönbellekten okunan token’ları sayar.input_tokensbu önbellek sayaçlarının dışında işlenen giriş token’larını sayar.
cache_read_input_tokens, kaç giriş token’ının
önbellekten okunduğunu bildirir. OpenAPI Prompt Cache
örneği, eksiksiz bir kurgusal referans içerir; bunu
reference.txt olarak kaydederek örneği deneyebilirsiniz.
Yanıtları akış olarak iletin
Server-Sent Events içinstream: true ayarlayın. SDK, metin parçalarını ulaştıkça sunar
:
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, içerik bloğu etkinlikleri, message_delta,
ve message_stop içerir. İçerik blokları metin, düşünme veya araç etkinliği içerebilir.
Bir metin bloğu için content_block_delta, bir text_delta içerir. Nihai kullanım bilgilerini okuyun
ve durma nedenini message_delta öğesinden okuyun.
Çaba denetimi
Akıl yürütme miktarını yönlendirmek içinoutput_config.effort ayarlayın. Bu örnekte
low kısa bir açıklama için kullanılır ve tamamlanmış akış mesajı beklenir:
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 öğesini ayrı olarak ayarlayın.
Sunucu araçlarını kullanın
Sunucu araçları API isteği sırasında çalışır ve sonuç bloklarını Claude’un yanıtıyla birlikte döndürür.- Web Fetch
- Web Search
Bir makaleyi getirin ve Claude’dan alınan belgeyi yanıtında kullanmasını isteyin.
Bu örnek, yanıtı Streaming ile alır ve hem son metni hem de
Yanıt, bir
web_fetch_tool_result bloğunu inceler: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 bloğunu bir web_fetch_tool_result bloğuyla eşleştirir.
Bu blok, getirilen belgeyi veya bir araç hatasını içerir.Resmî bir yayımlanma tarihi arayın ve Claude’dan kaynağını belirtmesini isteyin.
Bu örnek, yanıtı Streaming ile alır, son iletiyi toplar ve döndürülen arama
kaynaklarını yazdırır:Yanıt, bir
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 bloğunu bir web_search_tool_result bloğuyla eşleştirir.
Bu blok kaynakları içerir. Kaynak başlıklarını ve URL’leri bu sonuç bloğundan okuyun.İstemci aracı sonuçlarını döndürme
Bir istemci aracı için Claude,tool_use bloğu döndürür. Uygulama işlevinizi çalıştırın
ve sonucunu bir tool_result bloğunda, eşleşen tool_use_id ile gönderin.
İki istek arasındaki asistan içeriğinin tamamını koruyun.
Bu örnek, kurgusal bir sipariş sonucu sağlar ve Claude’dan bu sonucu kullanmasını ister:
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)
Yanıt örneği
Streaming olmayan bir istek bir mesaj nesnesi döndürür. Aşağıdaki örnek bunun açıklayıcı bir mesaj tanımlayıcısıyla metin ve kullanım alanlarını gösterir:{
"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 yanıtı tamamlar,
max_tokens çıktının sınıra ulaştığı anlamına gelir ve tool_use bir istemci aracı
sonucu ister. pause_turn döndüren bir sunucu aracı turunda,
döndürülen asistan içeriğiyle değişiklik yapmadan devam edin.Yetkilendirmeler
Başlıklar
Gövde
application/json
Yanıt
Successful response. When stream is true, the response is a stream of SSE events.
Son değiştirilme tarihi 8 Eylül 2026
⌘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
}
}
}