发送您的第一个请求

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:限制输出长度(英文约每个 token 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 # 导入

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 # 导入

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 # 导入

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 # 导入

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 模型入门

让我们一起练习吧!

Claude 模型入门

Preparing Video For Download...