リクエストの作成

Claude モデル入門

Nikhil Rangarajan

Data Scientist

Anthropic ライブラリとは?

  • Claude にアクセスするための公式 Python SDK

  • Claude とのやり取りを構造化

  • pip でインストール:

    pip install anthropic
    
  • ライブラリのインポート:

    import anthropic
    

プロンプト入力の後、Anthropic API 経由で Claude モデル とやり取りする図

Claude モデル入門

認証とセットアップ

$$

import anthropic

client = anthropic.Anthropic( api_key=os.getenv("ANTHROPIC_API_KEY") )

$$

🔑 コースの練習にキーは不要です

Claude モデル入門

プロンプトの送信

response = client.messages.create(

model="claude-sonnet-4-6",
max_tokens=100,
messages=[{"role": "user", "content": "What DataCamp course do you recommend to learn Claude?"}]
)
  • model: Claude Sonnet
  • max_tokens: 出力サイズの上限(英語では約 4 文字 / トークン)
    • トークン: モデルが処理するテキストの最小単位
  • messages: ユーザー入力から始まるやり取りのリスト
Claude モデル入門

モデルの出力を抽出

  • response: API レスポンス全体(構造化済み)
  • response.content:メッセージパーツのリストを返す
    [{'type': 'text', 
    'text': 'Claude is...'}]
    
  • response.content[0].text:アシスタントの返信
    "Claude is..."
    
Claude モデル入門

全体の流れ

import anthropic


client = anthropic.Anthropic()
response = client.messages.create( model="claude-sonnet-4-6", max_tokens=100, messages=[{"role": "user", "content": "Summarize the benefits of Claude in one sentence."}] )
print(response.content[0].text)
Claude モデル入門

全体の流れ

import anthropic #Importing

client = anthropic.Anthropic() 

response = client.messages.create( 
    model="claude-sonnet-4-6",
    max_tokens=100,
    messages=[{"role": "user", 
               "content": "Summarize the benefits of Claude in one sentence."}]
)

print(response.content[0].text) 
Claude モデル入門

全体の流れ

import anthropic #Importing

client = anthropic.Anthropic() #Initializing

response = client.messages.create( 
    model="claude-sonnet-4-6",
    max_tokens=100,
    messages=[{"role": "user", 
               "content": "Summarize the benefits of Claude in one sentence."}]
)

print(response.content[0].text) 
Claude モデル入門

全体の流れ

import anthropic #Importing

client = anthropic.Anthropic() #Initializing

response = client.messages.create( #Requesting
    model="claude-sonnet-4-6",
    max_tokens=100,
    messages=[{"role": "user", 
               "content": "Summarize the benefits of Claude in one sentence."}]
)

print(response.content[0].text) 
Claude モデル入門

全体の流れ

import anthropic #Importing

client = anthropic.Anthropic() #Initializing

response = client.messages.create( #Requesting
    model="claude-sonnet-4-6",
    max_tokens=100,
    messages=[{"role": "user", 
               "content": "Summarize the benefits of Claude in one sentence."}]
)

print(response.content[0].text) #Extracting
Claude モデル入門

練習しましょう!

Claude モデル入門

Preparing Video For Download...