Amazon Bedrock is a fully managed service that offers a choice of high-performing foundation models (FMs) from leading AI companies through a single API, along with a broad set of capabilities to build generative AI applications.
importboto3importjson# Initialize Bedrock clientbedrock=boto3.client('bedrock-runtime',region_name='us-east-1')# Invoke Claude modeldefinvoke_claude(prompt,max_tokens=1000):body=json.dumps({"prompt":f"\n\nHuman: {prompt}\n\nAssistant:","max_tokens_to_sample":max_tokens,"temperature":0.7,"top_p":0.9})response=bedrock.invoke_model(modelId='anthropic.claude-v2',body=body,contentType='application/json')response_body=json.loads(response['body'].read())returnresponse_body['completion']# Example usageresult=invoke_claude("Explain quantum computing in simple terms")print(result)
definvoke_claude_streaming(prompt):body=json.dumps({"prompt":f"\n\nHuman: {prompt}\n\nAssistant:","max_tokens_to_sample":1000,"temperature":0.7})response=bedrock.invoke_model_with_response_stream(modelId='anthropic.claude-v2',body=body,contentType='application/json')# Process streaming responseforeventinresponse['body']:chunk=json.loads(event['chunk']['bytes'])if'completion'inchunk:print(chunk['completion'],end='',flush=True)
Performance requirements: Guaranteed response times
Cost optimization: Lower per-token costs at scale
Production applications: Critical business applications
# Create provisioned model throughputresponse=bedrock.create_provisioned_model_throughput(modelUnits=1,modelId='anthropic.claude-v2',provisionedModelName='my-provisioned-model',commitmentDuration='OneMonth')
importnumpyasnpfromsentence_transformersimportSentenceTransformerclassRAGSystem:def__init__(self):self.embedding_model=SentenceTransformer('all-MiniLM-L6-v2')self.knowledge_base=[]self.embeddings=[]defadd_document(self,text,metadata=None):"""Add document to knowledge base"""embedding=self.embedding_model.encode(text)self.knowledge_base.append({'text':text,'metadata':metadataor{},'embedding':embedding})self.embeddings.append(embedding)defsearch(self,query,top_k=3):"""Search for relevant documents"""query_embedding=self.embedding_model.encode(query)# Calculate similaritiessimilarities=[]fordoc_embeddinginself.embeddings:similarity=np.dot(query_embedding,doc_embedding)/(np.linalg.norm(query_embedding)*np.linalg.norm(doc_embedding))similarities.append(similarity)# Get top-k most similar documentstop_indices=np.argsort(similarities)[-top_k:][::-1]return[self.knowledge_base[i]foriintop_indices]defgenerate_response(self,query):"""Generate response using RAG"""# Retrieve relevant contextrelevant_docs=self.search(query)context="\n".join([doc['text']fordocinrelevant_docs])# Create enhanced promptprompt=f""" Context information:{context} Question: {query} Please answer the question based on the provided context. """# Generate response with foundation modelreturninvoke_claude(prompt)
# Classification promptclassification_prompt="""Classify the following customer feedback into categories: positive, negative, or neutral.Feedback: "{feedback}"Classification: """# Summarization promptsummarization_prompt="""Please provide a concise summary of the following text in 2-3 sentences:Text: {text}Summary: """# Code generation promptcode_prompt="""Write a Python function that {description}.Requirements:- Include proper error handling- Add docstrings- Use type hintsCode: """
few_shot_prompt="""Classify movie reviews as positive or negative:Review: "This movie was absolutely fantastic!"Sentiment: PositiveReview: "I fell asleep halfway through. Boring!"Sentiment: NegativeReview: "The acting was great but the plot was confusing."Sentiment: NegativeReview: "{user_review}"Sentiment: """
cot_prompt="""Solve this step by step:Question: A restaurant has 24 tables. Each table can seat 4 people. If the restaurant is 75% full, how many people are dining?Let me think through this step by step:1) First, I need to find the total capacity2) Then calculate 75% of that capacity3) Step 1: Total capacity = 24 tables Γ 4 people per table = 96 peopleStep 2: 75% of 96 = 0.75 Γ 96 = 72 peopleTherefore, 72 people are dining.Now solve this problem:{problem}"""
expert_prompt="""You are a cybersecurity expert with 15 years of experience. A client asks: "{question}"Provide a detailed, professional response that includes:1. Technical explanation2. Potential risks3. Recommended solutions4. Best practicesResponse: """
# Calculate token costsdefcalculate_cost(input_tokens,output_tokens,model_id):# Pricing varies by model - example for Claudepricing={'anthropic.claude-v2':{'input':0.00001102,# per 1K input tokens'output':0.00003268# per 1K output tokens}}ifmodel_idinpricing:input_cost=(input_tokens/1000)*pricing[model_id]['input']output_cost=(output_tokens/1000)*pricing[model_id]['output']returninput_cost+output_costreturn0
importlogging# Set up logginglogging.basicConfig(level=logging.INFO)logger=logging.getLogger(__name__)definvoke_with_logging(prompt,model_id):logger.info(f"Invoking model {model_id}")logger.debug(f"Prompt: {prompt[:100]}...")try:response=invoke_model(prompt,model_id)logger.info(f"Successful invocation, response length: {len(response)}")returnresponseexceptExceptionase:logger.error(f"Model invocation failed: {str(e)}")raise