Skip to content

Instantly share code, notes, and snippets.

@Nunocky
Created May 11, 2025 05:32
Show Gist options
  • Save Nunocky/44e287655f4a4e49cc1201505ddabd2d to your computer and use it in GitHub Desktop.
Save Nunocky/44e287655f4a4e49cc1201505ddabd2d to your computer and use it in GitHub Desktop.
AWS Bedrockの Claudeでストリーミングレスポンスを取得
#!/usr/bin/env python3
import json
import os
import sys
import boto3
# モデルを定義
#modelId = "anthropic.claude-3-5-sonnet-20241022-v1" # Inference profile ARN ... NG
modelId = "apac.anthropic.claude-3-5-sonnet-20241022-v2:0" # Inference profile ID ... OK
# デバッグ用にログを有効化
boto3.set_stream_logger('', level=20) # INFO レベル
# Bedrockクライアントの作成
bedrock_runtime = boto3.client('bedrock-runtime')
# リクエストボディを定義
body = json.dumps({
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 1000,
"messages": [
{"role": "assistant", "content": "Hi, I'm Claude. How can I help you?"},
{
"role": "user",
"content": [{"type": "text", "text": "いろは歌を教えて"}]
}
]
})
# レスポンスを定義
response = bedrock_runtime.invoke_model_with_response_stream(body=body, modelId=modelId)
# ストリーミング出力
for event in response.get("body"):
chunk = json.loads(event["chunk"]["bytes"])
if chunk['type'] == 'content_block_delta' and chunk['delta']['type'] == 'text_delta':
print(chunk['delta']['text'], end="")
# ストリーミング終了後に改行
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment