欢迎大家再次来到小李哥的AI学习系列,本篇文章中我们将介绍和学习如何使用亚马逊云科技云端的Python SDK调用Claude 3.7 Sonnet的混合推理功能。本教程将带大家完成一个真实的案例场景,让大家能够在自己的应用程序中集成Claude的超能力,并且理解该模型的内部思考过程。
Anthropic最近推出的首个混合推理模型登上了AI行业的头条,大家是不是也很关心Claude在回答复杂问题时的内部运作方式?现在Claude 3.7 Sonnet的新推理功能让大家可以一窥其背后的思维过程。这一能力提升了Claude如何分析问题、拆解复杂问题并得出结论的AI透明度。
在本文章中,我们将构建一个Python语言的应用程序,并且调用Amazon Bedrock上这一强大的AI模型。大家将学习如何在API调用时启用推理功能、为应用分配合适的计算资源,并处理包含Claude内部推理过程的结构化响应。无论是调试提示词、验证计算结果,还是将Claude作为教育工具,理解其推理过程都能显著提升大家的AI交互体验。
如果大家已经熟悉Claude和Amazon Bedrock,只需要获取代码部分,大家可以直接跳转到第二章的项目实现操作细节。
什么是推理功能?
推理是Claude能够在回答问题之前,明确地逐步思考复杂问题的过程。启用该功能后,Claude不会直接给出最终答案,而是像人类解决问题时“自言自语”一样,完整展现其思考过程。
此功能使Claude能够:
- 将复杂问题拆解为可管理的组件
- 探索多种解决问题的方法
- 系统性分析信息并得出逻辑结论
- 展示其推理过程,尤其适用于数学或逻辑问题
- 识别自身思维中的潜在漏洞
推理功能对于需要多步骤思考去解决的问题尤为有用,例如复杂的数学计算、逻辑难题或需要细致分析的问答。通过揭示Claude的内部思维过程,大家可以更透明地理解其如何得出结论,从而增强信任并提供教育价值。
启用推理功能后,Claude会将部分计算资源(由大家的token预算决定)分配给这一明确的思考过程,并将其结果与最终答案一起返回给大家。这使大家能够前所未有地了解AI的思维链CoT,提升了传统AI模型遇到的低透明度问题。
实验前提条件
在开始本实验之前,请确保大家已具备以下条件:
- 拥有一个亚马逊云科技账户,并获得Amazon Bedrock的访问权限
- 安装了Python 3.x
- 已安装并配置亚马逊云科技命令行终端工具CLI
- 账户中已启用Claude 3.7 Sonnet访问权限
在撰写本文时,Claude 3.7可在亚马逊云科技平台上us-east-1、us-east-2和us-west-2区域使用。
设置依赖项
大家需要安装亚马逊云科技Python SDK(boto3)。以下是如何包含所需依赖项的方法:
pip install boto3>=1.37.0
或者在requirements.txt文件中添加以下内容:
boto3>=1.37.0
第1步:创建基础文件结构
创建一个新的Python文件(例如 claude_reasoning.py
),我们将在其中编写Claude的推理功能交互代码。
import boto3
from botocore.exceptions import ClientError
def reasoning_example():
# We'll implement this function in the next steps
pass
if __name__ == "__main__":
# We'll call our reasoning function here
pass
第2步:设置Amazon Bedrock客户端
首先,我们需要创建一个Bedrock运行时客户端,以处理API请求。在 reasoning_example()
函数中添加以下代码:
# Create the Amazon Bedrock runtime client
client = boto3.client("bedrock-runtime", region_name="us-east-1")
# Specify the model ID for Claude 3.7 Sonnet
model_id = "us.anthropic.claude-3-7-sonnet-20250219-v1:0"
第3步:为Claude创建消息
接下来,我们将创建一个简单的消息并发送给Claude:
# Create the message with the user's prompt
user_message = "Describe the purpose of a 'hello world' program in one line."
conversation = [
{
"role": "user",
"content": [{"text": user_message}],
}
]
第4步:配置推理参数
这里是关键步骤——我们需要启用推理功能并设置token预算:
budget_tokens
参数定义了Claude可以用于推理过程的最大token数量。大家可以根据提示词的复杂性调整此值。
# Configure reasoning parameters with a 2000 token budget
reasoning_config = {
"thinking": {
"type": "enabled",
"budget_tokens": 2000
}
}
第5步:发送请求至Claude
现在,我们将把提示词及推理配置发给Bedrock平台:
additionalModelRequestFields
参数允许我们传递推理配置。
# Send message and reasoning configuration to the model
response = client.converse(
modelId=model_id,
messages=conversation,
additionalModelRequestFields=reasoning_config
)
第6步:处理响应
Claude将返回其推理过程和最终答案,我们需要解析响应,并提取这些内容:
# Extract the list of content blocks from the model's response
content_blocks = response["output"]["message"]["content"]
reasoning = None
text = None
# Process each content block to find reasoning and response text
for block in content_blocks:
if "reasoningContent" in block:
reasoning = block["reasoningContent"]["reasoningText"]["text"]
if "text" in block:
text = block["text"]
return reasoning, text
第7步:展示结果
最后,我们将显示推理过程和最终答案。按照如下示例更新主函数:
if __name__ == "__main__":
# Execute the example and display reasoning and final response
reasoning, text = reasoning_example()
print("\n<thinking>")
print(reasoning)
print("</thinking>\n")
print(text)
完整代码
以下是完整的代码段:
import boto3
from botocore.exceptions import ClientError
"""
This example demonstrates how to use Anthropic Claude 3.7 Sonnet's reasoning capability
with Amazon Bedrock. It shows how to:
- Set up the Amazon Bedrock runtime client
- Create a message
- Configure reasoning parameters
- Send a request with reasoning enabled
- Process both the reasoning output and final response
"""
def reasoning_example():
# Create the Amazon Bedrock runtime client
client = boto3.client("bedrock-runtime", region_name="us-east-1")
# Specify the model ID. For the latest available models, see:
# https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html
model_id = "us.anthropic.claude-3-7-sonnet-20250219-v1:0"
# Create the message with the user's prompt
user_message = "Describe the purpose of a 'hello world' program in one line."
conversation = [
{
"role": "user",
"content": [{"text": user_message}],
}
]
# Configure reasoning parameters with a 2000 token budget
reasoning_config = {
"thinking": {
"type": "enabled",
"budget_tokens": 2000
}
}
try:
# Send message and reasoning configuration to the model
response = client.converse(
modelId=model_id,
messages=conversation,
additionalModelRequestFields=reasoning_config
)
# Extract the list of content blocks from the model's response
content_blocks = response["output"]["message"]["content"]
reasoning = None
text = None
# Process each content block to find reasoning and response text
for block in content_blocks:
if "reasoningContent" in block:
reasoning = block["reasoningContent"]["reasoningText"]["text"]
if "text" in block:
text = block["text"]
return reasoning, text
except (ClientError, Exception) as e:
print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
exit(1)
if __name__ == "__main__":
# Execute the example and display reasoning and final response
reasoning, text = reasoning_example()
print("\n<thinking>")
print(reasoning)
print("</thinking>\n")
print(text)
示例输出
运行此代码后,大家将会看到类似于以下的输出:
<thinking>
I need to explain the purpose of a "Hello World" program in a single line.A "Hello World" program is typically the simplest program that can be written in
a programming language. Its purpose is to:
1. Verify that the programming environment is set up correctly
2. Demonstrate the minimal syntax needed to create a functioning program
3. Provide a simple introduction to the language
4. Output the text "Hello, World!" or a similar messageI need to condense this information into a concise, one-line description that
captures the essence of what a "Hello World" program is for.
</thinking>A "Hello World" program serves as the simplest introduction to a programming
language by demonstrating basic syntax while verifying the environment works correctly.
总结
Claude最新推出的推理功能彻底改变了我们与AI的交互方式,使我们能够深入了解模型的思维过程。通过本文章中介绍的步骤和详细代码,大家现在可以在Amazon Bedrock上使用Python访问并利用这一强大功能。
该推理功能为提升AI透明度和信任性、优化AI输出的结果、深入理解AI交互的过程开辟了新的一种方式。对于要求更高的AI应用使用场景,大家可以考虑:
- 根据问题的复杂性调整token预算——更复杂的问题可能需要更大的推理预算,节约成本
- 使用推理输出验证多步计算任务或复杂分析流程
- 通过调整提示词对比不同的推理方法
- 将推理与Claude的其他能力(如函数调用、知识库等)结合,实现强大且更透明的AI解决方案
- 作为教育工具使用该推理功能,解决学术级、专业级别的问题
通过将推理功能集成到日常开发的AI应用中或者教育学习中,大家不仅可以获得答案,还能深入了解完整的解题过程。这种透明度有助于建立用户对AI的信任,并提供更加丰富和有价值的AI交互体验。