建立你的第一個請求

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 個字元。)
    • 權杖(token):模型處理的最小文字單位
  • 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...