{"id":"bedrock","name":"bedrock","summary":"生成AIのためのAWS Bedrock基盤モデル。基礎モデルの呼び出し、AIアプリケーションの構築、埋め込みの作成、モデルアクセスの設定、RAGパターンの実装などに使用されます。","body":"# AWS Bedrock\n\nAmazon Bedrock provides access to foundation models (FMs) from AI companies through a unified API. Build generative AI applications with text generation, embeddings, and image generation capabilities.\n\n## Table of Contents\n\n- [Core Concepts](#core-concepts)\n- [Common Patterns](#common-patterns)\n- [CLI Reference](#cli-reference)\n- [Best Practices](#best-practices)\n- [Troubleshooting](#troubleshooting)\n- [References](#references)\n\n## Core Concepts\n\n### Foundation Models\n\nPre-trained models available through Bedrock:\n- **Claude** (Anthropic): Text generation, analysis, coding\n- **Titan** (Amazon): Text, embeddings, image generation\n- **Llama** (Meta): Open-weight text generation\n- **Mistral**: Efficient text generation\n- **Stable Diffusion** (Stability AI): Image generation\n\n### Model Access\n\nModels must be enabled in your account before use:\n- Request access in Bedrock console\n- Some models require acceptance of EULAs\n- Access is region-specific\n\n### Inference Types\n\n| Type | Use Case | Pricing |\n|------|----------|---------|\n| **On-Demand** | Variable workloads | Per token |\n| **Provisioned Throughput** | Consistent high-volume | Hourly commitment |\n| **Batch Inference** | Async large-scale | Discounted per token |\n\n## Common Patterns\n\n### Invoke Model (Text Generation)\n\n**AWS CLI:**\n\n```bash\n# Invoke Claude\naws bedrock-runtime invoke-model \\\n  --model-id anthropic.claude-3-sonnet-20240229-v1:0 \\\n  --content-type application/json \\\n  --accept application/json \\\n  --body '{\n    \"anthropic_version\": \"bedrock-2023-05-31\",\n    \"max_tokens\": 1024,\n    \"messages\": [\n      {\"role\": \"user\", \"content\": \"Explain AWS Lambda in 3 sentences.\"}\n    ]\n  }' \\\n  response.json\n\ncat response.json | jq -r '.content[0].text'\n```\n\n**boto3:**\n\n```python\nimport boto3\nimport json\n\nbedrock = boto3.client('bedrock-runtime')\n\ndef invoke_claude(prompt, max_tokens=1024):\n    response = bedrock.invoke_model(\n        modelId='anthropic.claude-3-sonnet-20240229-v1:0',\n        contentType='application/json',\n        accept='application/json',\n        body=json.dumps({\n            'anthropic_version': 'bedrock-2023-05-31',\n            'max_tokens': max_tokens,\n            'messages': [\n                {'role': 'user', 'content': prompt}\n            ]\n        })\n    )\n\n    result = json.loads(response['body'].read())\n    return result['content'][0]['text']\n\n# Usage\nresponse = invoke_claude('What is Amazon S3?')\nprint(response)\n```\n\n### Streaming Response\n\n```python\nimport boto3\nimport json\n\nbedrock = boto3.client('bedrock-runtime')\n\ndef stream_claude(prompt):\n    response = bedrock.invoke_model_with_response_stream(\n        modelId='anthropic.claude-3-sonnet-20240229-v1:0',\n        contentType='application/json',\n        accept='application/json',\n        body=json.dumps({\n            'anthropic_version': 'bedrock-2023-05-31',\n            'max_tokens': 1024,\n            'messages': [\n                {'role': 'user', 'content': prompt}\n            ]\n        })\n    )\n\n    for event in response['body']:\n        chunk = json.loads(event['chunk']['bytes'])\n        if chunk['type'] == 'content_block_delta':\n            yield chunk['delta'].get('text', '')\n\n# Usage\nfor text in stream_claude('Write a haiku about cloud computing.'):\n    print(text, end='', flush=True)\n```\n\n### Generate Embeddings\n\n```python\nimport boto3\nimport json\n\nbedrock = boto3.client('bedrock-runtime')\n\ndef get_embedding(text):\n    response = bedrock.invoke_model(\n        modelId='amazon.titan-embed-text-v2:0',\n        contentType='application/json',\n        accept='application/json',\n        body=json.dumps({\n            'inputText': text,\n            'dimensions': 1024,\n            'normalize': True\n        })\n    )\n\n    result = json.loads(response['body'].read())\n    return result['embedding']\n\n# Usage\nembedding = get_embedding('AWS Lambda is a serverless compute service.')\nprint(f'Embedding dimension: {len(embedding)}')\n```\n\n### Conversation with History\n\n```python\nimport boto3\nimport json\n\nbedrock = boto3.client('bedrock-runtime')\n\nclass Conversation:\n    def __init__(self, system_prompt=None):\n        self.messages = []\n        self.system = system_prompt\n\n    def chat(self, user_message):\n        self.messages.append({\n            'role': 'user',\n            'content': user_message\n        })\n\n        body = {\n            'anthropic_version': 'bedrock-2023-05-31',\n            'max_tokens': 1024,\n            'messages': self.messages\n        }\n\n        if self.system:\n            body['system'] = self.system\n\n        response = bedrock.invoke_model(\n            modelId='anthropic.claude-3-sonnet-20240229-v1:0',\n            contentType='application/json',\n            accept='application/json',\n            body=json.dumps(body)\n        )\n\n        result = json.loads(response['body'].read())\n        assistant_message = result['content'][0]['text']\n\n        self.messages.append({\n            'role': 'assistant',\n            'content': assistant_message\n        })\n\n        return assistant_message\n\n# Usage\nconv = Conversation(system_prompt='You are an AWS solutions architect.')\nprint(conv.chat('What database should I use for a chat application?'))\nprint(conv.chat('What about for time-series data?'))\n```\n\n### List Available Models\n\n```bash\n# List all foundation models\naws bedrock list-foundation-models \\\n  --query 'modelSummaries[*].[modelId,modelName,providerName]' \\\n  --output table\n\n# Filter by provider\naws bedrock list-foundation-models \\\n  --by-provider anthropic \\\n  --query 'modelSummaries[*].modelId'\n\n# Get model details\naws bedrock get-foundation-model \\\n  --model-identifier anthropic.claude-3-sonnet-20240229-v1:0\n```\n\n### Request Model Access\n\n```bash\n# List model access status\naws bedrock list-foundation-model-agreement-offers \\\n  --model-id anthropic.claude-3-sonnet-20240229-v1:0\n```\n\n## CLI Reference\n\n### Bedrock (Control Plane)\n\n| Command | Description |\n|---------|-------------|\n| `aws bedrock list-foundation-models` | List available models |\n| `aws bedrock get-foundation-model` | Get model details |\n| `aws bedrock list-custom-models` | List fine-tuned models |\n| `aws bedrock create-model-customization-job` | Start fine-tuning |\n| `aws bedrock list-provisioned-model-throughputs` | List provisioned capacity |\n\n### Bedrock Runtime (Data Plane)\n\n| Command | Description |\n|---------|-------------|\n| `aws bedrock-runtime invoke-model` | Invoke model synchronously |\n| `aws bedrock-runtime invoke-model-with-response-stream` | Invoke with streaming |\n| `aws bedrock-runtime converse` | Multi-turn conversation API |\n| `aws bedrock-runtime converse-stream` | Streaming conversation |\n\n### Bedrock Agent Runtime\n\n| Command | Description |\n|---------|-------------|\n| `aws bedrock-agent-runtime invoke-agent` | Invoke a Bedrock agent |\n| `aws bedrock-agent-runtime retrieve` | Query knowledge base |\n| `aws bedrock-agent-runtime retrieve-and-generate` | RAG query |\n\n## Best Practices\n\n### Cost Optimization\n\n- **Use appropriate models**: Smaller models for simple tasks\n- **Set max_tokens**: Limit output length when possible\n- **Cache responses**: For repeated identical queries\n- **Batch when possible**: Use batch inference for bulk processing\n- **Monitor usage**: Set up CloudWatch alarms for cost\n\n### Performance\n\n- **Use streaming**: For better user experience with long outputs\n- **Connection pooling**: Reuse boto3 clients\n- **Regional deployment**: Use closest region to reduce latency\n- **Provisioned throughput**: For consistent high-volume workloads\n\n### Security\n\n- **Least privilege IAM**: Only grant needed model access\n- **VPC endpoints**: Keep traffic private\n- **Guardrails**: Implement content filtering\n- **Audit with CloudTrail**: Track model invocations\n\n### IAM Permissions\n\n```json\n{\n  \"Version\": \"2012-10-17\",\n  \"Statement\": [\n    {\n      \"Effect\": \"Allow\",\n      \"Action\": [\n        \"bedrock:InvokeModel\",\n        \"bedrock:InvokeModelWithResponseStream\"\n      ],\n      \"Resource\": [\n        \"arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-3-sonnet-20240229-v1:0\",\n        \"arn:aws:bedrock:us-east-1::foundation-model/amazon.titan-embed-text-v2:0\"\n      ]\n    }\n  ]\n}\n```\n\n## Troubleshooting\n\n### AccessDeniedException\n\n**Causes:**\n- Model access not enabled in console\n- IAM policy missing `bedrock:InvokeModel`\n- Wrong model ID or region\n\n**Debug:**\n\n```bash\n# Check model access status\naws bedrock list-foundation-models \\\n  --query 'modelSummaries[?modelId==`anthropic.claude-3-sonnet-20240229-v1:0`]'\n\n# Test IAM permissions\naws iam simulate-principal-policy \\\n  --policy-source-arn arn:aws:iam::123456789012:role/my-role \\\n  --action-names bedrock:InvokeModel \\\n  --resource-arns \"arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-3-sonnet-20240229-v1:0\"\n```\n\n### ModelNotReadyException\n\n**Cause:** Model is still being provisioned or temporarily unavailable.\n\n**Solution:** Implement retry with exponential backoff:\n\n```python\nimport time\nfrom botocore.exceptions import ClientError\n\ndef invoke_with_retry(bedrock, body, max_retries=3):\n    for attempt in range(max_retries):\n        try:\n            return bedrock.invoke_model(\n                modelId='anthropic.claude-3-sonnet-20240229-v1:0',\n                body=json.dumps(body)\n            )\n        except ClientError as e:\n            if e.response['Error']['Code'] == 'ModelNotReadyException':\n                time.sleep(2 ** attempt)\n            else:\n                raise\n    raise Exception('Max retries exceeded')\n```\n\n### ThrottlingException\n\n**Causes:**\n- Exceeded on-demand quota\n- Too many concurrent requests\n\n**Solutions:**\n- Request quota increase\n- Implement exponential backoff\n- Consider provisioned throughput\n\n### ValidationException\n\n**Common issues:**\n- Invalid model ID\n- Malformed request body\n- max_tokens exceeds model limit\n\n**Debug:**\n\n```python\n# Check model-specific requirements\naws bedrock get-foundation-model \\\n  --model-identifier anthropic.claude-3-sonnet-20240229-v1:0 \\\n  --query 'modelDetails.inferenceTypesSupported'\n```\n\n## References\n\n- [Bedrock User Guide](https://docs.aws.amazon.com/bedrock/latest/userguide/)\n- [Bedrock API Reference](https://docs.aws.amazon.com/bedrock/latest/APIReference/)\n- [Bedrock Runtime API](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Amazon_Bedrock_Runtime.html)\n- [Model Parameters](https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters.html)\n- [Bedrock Pricing](https://aws.amazon.com/bedrock/pricing/)","author":"@itsmostafa","ownerProfile":null,"authorContacts":null,"sourceUrl":"https://github.com/itsmostafa/aws-agent-skills/tree/main/skills/bedrock","license":"MIT","category":null,"lang":"en","tokens":2552,"stars":0,"calls30d":2,"claimed":false,"visibility":"public","origin":"crawler","version":"0.1.0","createdAt":"2026-08-22","updatedAt":"2026-08-22","files":[{"path":"model-invocation.md","size":13261,"sha256":"ba3275763c6bb8f72ebec41dcb069179b7d7db401e218d4e95714637ec44b107"}],"requires":{"mcp":[],"tools":[]},"safety":{"flags":[],"scannedAt":"2026-08-22","hasScripts":false,"networkEndpoints":["aws.amazon.com","docs.aws.amazon.com"]}}