Generate text by using a Claude model from Anthropic

Use the Anthropic Vertex AI SDK to send a prompt to an Anthropic Claude model and then display the generated text.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

Python

Before trying this sample, follow the Python setup instructions in the Vertex AI quickstart using client libraries . For more information, see the Vertex AI Python API reference documentation .

To authenticate to Vertex AI, set up Application Default Credentials. For more information, see Set up authentication for a local development environment .

  # TODO(developer): Vertex AI SDK - uncomment below & run 
 # pip3 install --upgrade --user google-cloud-aiplatform 
 # gcloud auth application-default login 
 # pip3 install -U 'anthropic[vertex]' 
 # TODO(developer): Update and un-comment below line 
 # PROJECT_ID = "your-project-id" 
 from 
  
 anthropic 
  
 import 
 AnthropicVertex 
 client 
 = 
 AnthropicVertex 
 ( 
 project_id 
 = 
 PROJECT_ID 
 , 
 region 
 = 
 "us-east5" 
 ) 
 message 
 = 
 client 
 . 
 messages 
 . 
 create 
 ( 
 model 
 = 
 "claude-3-5-sonnet-v2@20241022" 
 , 
 max_tokens 
 = 
 1024 
 , 
 messages 
 = 
 [ 
 { 
 "role" 
 : 
 "user" 
 , 
 "content" 
 : 
 "Send me a recipe for banana bread." 
 , 
 } 
 ], 
 ) 
 print 
 ( 
 message 
 . 
 model_dump_json 
 ( 
 indent 
 = 
 2 
 )) 
 # Example response: 
 # { 
 #   "id": "msg_vrtx_0162rhgehxa9rvJM5BSVLZ9j", 
 #   "content": [ 
 #     { 
 #       "text": "Here's a simple recipe for delicious banana bread:\n\nIngredients:\n- 2-3 ripe bananas... 
 #   ... 
 

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser .

Create a Mobile Website
View Site in Mobile | Classic
Share by: