Claude Code × Amazon Bedrock गाइड: AWS पर Claude को सुरक्षित प्रोडक्शन में चलाएं
Claude Code और Amazon Bedrock से production Claude बनाएं: IAM, Converse API, logs, Guardrails और cost control.
Claude के साथ prototype बनाना हो तो Anthropic API को सीधे call करना सबसे आसान लगता है। लेकिन AWS production में बात अलग हो जाती है: API key management, IAM boundaries, audit logs, cost attribution, data retention, retry policy और quotas सब समझाने पड़ते हैं। इसी जगह Amazon Bedrock के ज़रिए Claude चलाना व्यावहारिक विकल्प बनता है।
Amazon Bedrock AWS का managed foundation model service है। सरल भाषा में, यह Claude को AWS identity, permissions, logging, billing और operations के अंदर रखकर call करने देता है। Claude Code यहां बहुत मदद करता है, लेकिन उससे सिर्फ “चलता हुआ demo” न बनवाएं। उससे IAM, model invocation, Guardrails, logs, error handling और cost limits सहित reviewable code बनवाएं।
Masa ने real projects में एक बात सीखी: Bedrock demo जल्दी चल जाता है, पर production review अलग सवाल पूछती है। कौन सा role model call करेगा? कौन से model IDs allowed हैं? throttling पर क्या होगा? prompts logs में जाएंगे या नहीं? टीम के हिसाब से cost कैसे track होगी? यह guide उन्हीं सवालों को code और Claude Code prompt में बदलती है।
यह लेख 3 जून 2026 तक की AWS official documentation पर आधारित है। Bedrock model IDs, Regions, quotas और pricing बदल सकते हैं, इसलिए deploy करने से पहले official docs जरूर देखें।
- Amazon Bedrock User Guide
- Inference using Converse API
- Request access to models
- Get information about foundation models
- How Amazon Bedrock Guardrails works
- Model invocation logging
- Troubleshooting Amazon Bedrock API error codes
- Prompt caching
- IAM principal attribution
Production architecture
Claude Code से सीधे “Bedrock chat API जोड़ो” न कहें। पहले caller, runtime, model, Guardrails, logs और cost attribution तय करें।
flowchart LR
U["User / Admin UI"] --> A["API Gateway or ALB"]
A --> R["Lambda or ECS task"]
R --> G["Input validation and budget guard"]
G --> B["Amazon Bedrock Runtime<br/>Converse / ConverseStream"]
B --> C["Claude model"]
R --> L["App logs<br/>CloudWatch Logs"]
B --> M["Model invocation logs<br/>CloudWatch Logs or S3"]
R --> K["Knowledge Bases<br/>optional RAG"]
R --> Q["Cost Explorer / CUR<br/>IAM principal attribution"]
Converse API Bedrock का unified chat-style API है। Guardrails configured safety policies के आधार पर user input और model output को evaluate करता है। model invocation logging invocation data को CloudWatch Logs या S3 में भेज सकता है। IAM principal attribution Bedrock cost को IAM users और roles के हिसाब से देखने में मदद करता है।
सही use cases
पहला use case internal documentation Q&A है। Runbooks, product specs और support procedures को S3-backed Knowledge Bases में रखें, relevant chunks retrieve करें और Claude से citations के साथ answer बनवाएं। इसे RAG कहते हैं, यानी retrieval augmented generation: model अपने general knowledge के साथ आपके data से मिले context पर जवाब देता है।
दूसरा use case support reply draft है। Claude customer question, plan details और approved templates से जवाब का draft बनाता है, फिर operator उसे approve करता है। पूरी automation से पहले human review, Guardrails, PII handling और audit logs रखें।
तीसरा use case engineering operations assistant है। यह CloudWatch logs summarize कर सकता है, deployment checklist बना सकता है, incident notes draft कर सकता है और runbook को tasks में बदल सकता है। Claude Code API, Lambda, IAM, tests और docs को एक साथ update कर सकता है, इसलिए team standardization आसान होती है।
चौथा use case ClaudeCodeLab जैसे content site operations हैं। Article QA, description length, internal links और code block review को AWS IAM और billing के अंदर चलाया जा सकता है। अगर content quality revenue से जुड़ी है, तो Claude Code API cost guide और verification receipt workflow भी देखें।
Setup
आपको Node.js 20+, AWS CLI credentials, Bedrock access वाला AWS account और target Region में available Anthropic model चाहिए। कुछ accounts में Anthropic models के लिए first-time use details, AWS Marketplace permissions और valid payment method की जरूरत हो सकती है।
किसी article से model ID copy करके hard-code न करें। अपने account में available models list करें और chosen ID environment variable में रखें।
export AWS_REGION=us-east-1
aws bedrock list-foundation-models \
--region "$AWS_REGION" \
--query "modelSummaries[?providerName=='Anthropic'].[modelId,modelName]" \
--output table
export BEDROCK_MODEL_ID="anthropic.claude-sonnet-4-20250514-v1:0"
aws bedrock get-foundation-model \
--region "$AWS_REGION" \
--model-identifier "$BEDROCK_MODEL_ID" \
--query "modelDetails.{input:inputModalities,output:outputModalities,streaming:responseStreamingSupported}"
एक छोटा TypeScript project बनाएं।
mkdir bedrock-claude-lab
cd bedrock-claude-lab
npm init -y
npm install @aws-sdk/client-bedrock @aws-sdk/client-bedrock-runtime @aws-sdk/client-bedrock-agent-runtime
npm install --save-dev typescript tsx @types/node
npx tsc --init --module NodeNext --moduleResolution NodeNext --target ES2022
mkdir -p src/lambda
package.json में scripts जोड़ें।
{
"type": "module",
"scripts": {
"chat": "tsx src/chat.ts",
"stream": "tsx src/stream.ts",
"typecheck": "tsc --noEmit"
}
}
IAM baseline
Converse API इस्तेमाल करने पर भी IAM में model invocation permissions चाहिए। Non-streaming call के लिए bedrock:InvokeModel, streaming के लिए bedrock:InvokeModelWithResponseStream चाहिए। Application logs permissions और Bedrock model invocation logging settings को अलग रखें।
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ListBedrockModelsForStartupCheck",
"Effect": "Allow",
"Action": ["bedrock:ListFoundationModels", "bedrock:GetFoundationModel"],
"Resource": "*"
},
{
"Sid": "InvokeOnlyApprovedClaudeModels",
"Effect": "Allow",
"Action": ["bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream"],
"Resource": [
"arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-*",
"arn:aws:bedrock:us-west-2::foundation-model/anthropic.claude-*",
"arn:aws:bedrock:us-east-1:123456789012:inference-profile/*"
]
},
{
"Sid": "ApplyApprovedGuardrail",
"Effect": "Allow",
"Action": ["bedrock:ApplyGuardrail"],
"Resource": "arn:aws:bedrock:us-east-1:123456789012:guardrail/your-guardrail-id"
}
]
}
Account ID, Regions, Guardrail ID और model scope को अपने environment के हिसाब से बदलें। Cross-Region inference में inference profile और destination model ARNs भी policy में आते हैं। Least privilege review के लिए Claude Code AWS IAM guide पढ़ें।
Claude invocation
Production detail है requestMetadata। AWS इसे model invocation logs filter करने के लिए उपयोगी बताता है, इसलिए request ID, feature और caller category जोड़ें।
// src/bedrock-client.ts
import { randomUUID } from "node:crypto";
import {
BedrockRuntimeClient,
ConverseCommand,
ConverseStreamCommand,
type ConverseCommandInput,
} from "@aws-sdk/client-bedrock-runtime";
export const AWS_REGION = process.env.AWS_REGION ?? "us-east-1";
export const BEDROCK_MODEL_ID =
process.env.BEDROCK_MODEL_ID ?? "anthropic.claude-sonnet-4-20250514-v1:0";
export const bedrock = new BedrockRuntimeClient({
region: AWS_REGION,
maxAttempts: Number(process.env.BEDROCK_MAX_ATTEMPTS ?? "3"),
});
type AskClaudeInput = {
prompt: string;
system?: string;
maxTokens?: number;
temperature?: number;
userId?: string;
feature?: string;
};
function optionalGuardrail(): ConverseCommandInput["guardrailConfig"] | undefined {
const guardrailIdentifier = process.env.BEDROCK_GUARDRAIL_ID;
if (!guardrailIdentifier) return undefined;
return {
guardrailIdentifier,
guardrailVersion: process.env.BEDROCK_GUARDRAIL_VERSION ?? "DRAFT",
trace: "enabled",
};
}
export async function askClaude(input: AskClaudeInput) {
const requestId = randomUUID();
const startedAt = Date.now();
const response = await bedrock.send(
new ConverseCommand({
modelId: BEDROCK_MODEL_ID,
system: input.system ? [{ text: input.system }] : undefined,
messages: [{ role: "user", content: [{ text: input.prompt }] }],
inferenceConfig: {
maxTokens: input.maxTokens ?? 800,
temperature: input.temperature ?? 0.2,
},
guardrailConfig: optionalGuardrail(),
requestMetadata: {
requestId,
feature: input.feature ?? "local-cli",
userId: input.userId ?? "anonymous",
},
})
);
const text =
response.output?.message?.content
?.map((block: { text?: string }) => block.text ?? "")
.join("") ?? "";
console.log(
JSON.stringify({
level: "info",
event: "bedrock_converse",
requestId,
modelId: BEDROCK_MODEL_ID,
latencyMs: Date.now() - startedAt,
stopReason: response.stopReason,
usage: response.usage,
metrics: response.metrics,
})
);
return { text, usage: response.usage, stopReason: response.stopReason, requestId };
}
export async function streamClaude(prompt: string) {
const response = await bedrock.send(
new ConverseStreamCommand({
modelId: BEDROCK_MODEL_ID,
messages: [{ role: "user", content: [{ text: prompt }] }],
inferenceConfig: { maxTokens: 1200, temperature: 0.2 },
guardrailConfig: optionalGuardrail(),
requestMetadata: { feature: "stream-cli", requestId: randomUUID() },
})
);
if (!response.stream) throw new Error("Bedrock did not return a stream.");
for await (const event of response.stream) {
const text = event.contentBlockDelta?.delta?.text;
if (text) process.stdout.write(text);
if (event.metadata?.usage) {
process.stderr.write(`\nusage=${JSON.stringify(event.metadata.usage)}\n`);
}
}
}
// src/chat.ts
import { askClaude } from "./bedrock-client.js";
const prompt = process.argv.slice(2).join(" ").trim();
if (!prompt) {
console.error('Usage: npm run chat -- "Summarize Amazon Bedrock in three bullets"');
process.exit(1);
}
const result = await askClaude({
prompt,
system: "You are a concise AWS assistant. If you are unsure, say what to verify.",
maxTokens: 600,
feature: "developer-chat",
});
console.log(result.text);
// src/stream.ts
import { streamClaude } from "./bedrock-client.js";
const prompt = process.argv.slice(2).join(" ").trim();
if (!prompt) {
console.error('Usage: npm run stream -- "Write a deployment checklist"');
process.exit(1);
}
await streamClaude(prompt);
Run करें।
export AWS_REGION=us-east-1
export BEDROCK_MODEL_ID="anthropic.claude-sonnet-4-20250514-v1:0"
npm run chat -- "Amazon Bedrock को तीन lines में समझाओ"
npm run stream -- "Bedrock production checklist बनाओ"
npm run typecheck
Lambda pattern
Lambda में client को handler के बाहर initialize करें, input validate करें और maxTokens server side limit करें।
// src/lambda/assistant-handler.ts
import { askClaude } from "../bedrock-client.js";
type ApiEvent = {
body?: string | null;
requestContext?: { requestId?: string };
};
const headers = { "content-type": "application/json; charset=utf-8" };
export const handler = async (event: ApiEvent) => {
try {
const body = JSON.parse(event.body ?? "{}") as {
prompt?: string;
maxTokens?: number;
userId?: string;
};
if (!body.prompt || body.prompt.length > 8000) {
return {
statusCode: 400,
headers,
body: JSON.stringify({ error: "prompt is required and must be <= 8000 chars" }),
};
}
const result = await askClaude({
prompt: body.prompt,
maxTokens: Math.min(body.maxTokens ?? 800, 1200),
userId: body.userId ?? "anonymous",
feature: "support-assistant",
});
return {
statusCode: 200,
headers,
body: JSON.stringify({
text: result.text,
usage: result.usage,
stopReason: result.stopReason,
requestId: result.requestId,
}),
};
} catch (error) {
const name =
typeof error === "object" && error && "name" in error ? String(error.name) : "UnknownError";
const retryable = ["ThrottlingException", "ServiceUnavailableException", "InternalServerException"].includes(name);
console.error(JSON.stringify({ level: "error", event: "assistant_failed", name, retryable }));
return {
statusCode: retryable ? 503 : 500,
headers,
body: JSON.stringify({ error: retryable ? "Please retry later" : "Generation failed" }),
};
}
};
ValidationException को blindly retry न करें; यह अक्सर input या parameter issue होता है। ThrottlingException और ServiceUnavailableException को exponential backoff और jitter से retry किया जा सकता है। Serverless flow के लिए Claude Code AWS Lambda guide देखें।
Knowledge Bases के साथ RAG
Internal document chat के लिए अपना vector store बनाने से पहले Bedrock Knowledge Bases से शुरू करना practical है। यह citations सहित answers दे सकता है। ध्यान रखें: Guardrails input और generated response पर लागू होता है, retrieved references पर नहीं। Sensitive documents को S3, KMS, IAM और data classification से पहले restrict करें।
// src/rag.ts
import {
BedrockAgentRuntimeClient,
RetrieveAndGenerateCommand,
} from "@aws-sdk/client-bedrock-agent-runtime";
const agentRuntime = new BedrockAgentRuntimeClient({
region: process.env.AWS_REGION ?? "us-east-1",
});
export async function askKnowledgeBase(question: string) {
const knowledgeBaseId = process.env.BEDROCK_KNOWLEDGE_BASE_ID;
const modelArn = process.env.BEDROCK_GENERATION_MODEL_ARN;
if (!knowledgeBaseId || !modelArn) {
throw new Error("Set BEDROCK_KNOWLEDGE_BASE_ID and BEDROCK_GENERATION_MODEL_ARN");
}
const response = await agentRuntime.send(
new RetrieveAndGenerateCommand({
input: { text: question },
retrieveAndGenerateConfiguration: {
type: "KNOWLEDGE_BASE",
knowledgeBaseConfiguration: {
knowledgeBaseId,
modelArn,
retrievalConfiguration: {
vectorSearchConfiguration: { numberOfResults: 5 },
},
},
},
})
);
const sources =
response.citations
?.flatMap((citation) => citation.retrievedReferences ?? [])
.map((reference) => reference.location?.s3Location?.uri)
.filter(Boolean) ?? [];
return { answer: response.output?.text ?? "", sources };
}
Logs और cost
दो logging layers रखें। Application logs में requestId, feature, caller type, model ID, usage, latency और stop reason रखें। Raw prompts तभी store करें जब privacy और retention policy अनुमति देती हो।
Bedrock model invocation logging CloudWatch Logs या S3 में लिख सकता है। Audit और debugging में मदद मिलती है, पर sensitive inputs और outputs भी store हो सकते हैं। Retention, encryption, S3 lifecycle और access control पहले तय करें।
Cost control API layer पर maxTokens limit करने से शुरू होता है। Task complexity के हिसाब से model चुनें, usage log करें और IAM principal attribution से role-wise cost देखें। Prompt caching लंबे और repeated context में मदद करता है, लेकिन छोटे या हर बार बदलते prompts में कम असर देता है।
Claude Code prompt
claude -p "
इस repository में Amazon Bedrock के जरिए Claude invocation जोड़ें।
Requirements:
- AWS SDK v3 Converse API इस्तेमाल करें
- model ID BEDROCK_MODEL_ID से पढ़ें
- AWS_REGION न हो तो us-east-1 default रखें
- server side maxTokens को 1200 तक cap करें
- requestMetadata में requestId, feature, userId जोड़ें
- BEDROCK_GUARDRAIL_ID हो तभी guardrailConfig जोड़ें
- usage, latencyMs, stopReason को JSON log करें
- ValidationException retry न करें
- ThrottlingException और ServiceUnavailableException को retryable मानें
- README में least-privilege IAM policy लिखें
- tests में Bedrock client mock करें; real API call न करें
Editing से पहले plan दिखाएं, फिर typecheck और test results report करें।
"
आम pitfalls
पहला pitfall है model access verify किए बिना code लिखना। पहले list-foundation-models और छोटा Converse request चलाएं।
दूसरा है article से model ID copy करके hard-code करना। Bedrock model IDs और Region support बदलते हैं। Environment variable और startup validation रखें।
तीसरा है Guardrails को correctness guarantee मान लेना। यह safety policies के लिए है, domain validation, authorization और human review का replacement नहीं।
चौथा है बहुत ज्यादा logging। Full prompts debug में मदद करते हैं, पर personal या internal data लंबे समय के logs में जा सकता है।
पांचवां है गलत errors retry करना। Validation errors में input या code fix चाहिए; throttling और temporary service errors retry हो सकते हैं।
छठा है cost control केवल frontend में रखना। Real limits API layer में enforce करें।
Monetization path
Bedrock content की value SDK snippet में नहीं, demo से production तक जाने में है: IAM, logs, cost, Guardrails, review और team rollout. Reusable templates के लिए ClaudeCodeLab products देखें। Real repository में CLAUDE.md, IAM review, verification receipts और CI gates लागू करने के लिए Claude Code training and consultation उपयोगी है।
Related articles: Claude Code AWS Lambda, Claude Code AWS IAM, Claude Code API cost guide और verification receipt workflow।
Practical result
इस pattern को आजमाने पर सबसे बड़ा सुधार extra abstraction से नहीं, बल्कि Claude Code को दिए गए prompt से आया। “model ID env से”, “usage log करना”, “ValidationException retry नहीं”, “Guardrails env से optional”, और “IAM policy README में” लिखने पर diff छोटा हुआ और review आसान हुआ। Bedrock की सफलता SDK याद करने से कम, production constraints पहले साफ करने से ज्यादा जुड़ी है।
मुफ़्त PDF: Claude Code cheatsheet
Email डालें और commands, review habits तथा safe workflow वाली एक-page PDF पाएँ.
हम आपका data सुरक्षित रखते हैं और spam नहीं भेजते.
लेखक के बारे में
Masa
Claude Code workflow और team adoption पर काम करने वाला engineer.
संबंधित लेख
Claude Code Obsidian to CLAUDE.md workflow: context बार-बार न समझाएं
Obsidian notes को CLAUDE.md operating notes में बदलकर Claude Code sessions को resume करना आसान बनाएं.
Claude Code Revenue CTA Routing: article से PDF, Gumroad और consultation तक
Reader intent के आधार पर free PDF, Gumroad products और consultation तक CTA route करने वाला workflow.
Claude Code टीम हैंडऑफ नियम: review proof, permissions, rollback और revenue path
Claude Code टीम काम के लिए evidence, permission rules, rollback, free PDF, Gumroad और consultation path वाला handoff.