Amazon Bedrock Runtime-Beispiele mit SDK for Python (Boto3) - AWS SDK-Codebeispiele

Weitere AWS SDK-Beispiele sind im Repo AWS Doc SDK Examples GitHub verfügbar.

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

Amazon Bedrock Runtime-Beispiele mit SDK for Python (Boto3)

Die folgenden Codebeispiele zeigen Ihnen, wie Sie AWS SDK for Python (Boto3) mit Amazon Bedrock Runtime Aktionen ausführen und allgemeine Szenarien implementieren.

Aktionen sind Codeauszüge aus größeren Programmen und müssen im Kontext ausgeführt werden. Während Aktionen Ihnen zeigen, wie Sie einzelne Servicefunktionen aufrufen, können Sie Aktionen im Kontext der zugehörigen Szenarien und serviceübergreifenden Beispiele sehen.

Szenarien sind Codebeispiele, die Ihnen zeigen, wie Sie eine bestimmte Aufgabe ausführen können, indem Sie mehrere Funktionen innerhalb desselben Services aufrufen.

Jedes Beispiel enthält einen Link zu GitHub, wo Sie Anweisungen zur Einrichtung und Ausführung des Codes im Kontext finden.

AI21 Labs Jurassic-2

Das folgende Codebeispiel zeigt, wie mithilfe der Converse-API von Bedrock eine Textnachricht an AI21 Labs Jurassic-2 gesendet wird.

SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Senden Sie mithilfe der Converse-API von Bedrock eine Textnachricht an AI21 Labs Jurassic-2.

# Use the Conversation API to send a text message to AI21 Labs Jurassic-2. import boto3 from botocore.exceptions import ClientError # Create a Bedrock Runtime client in the AWS Region you want to use. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Jurassic-2 Mid. model_id = "ai21.j2-mid-v1" # Start a conversation with the user message. user_message = "Describe the purpose of a 'hello world' program in one line." conversation = [ { "role": "user", "content": [{"text": user_message}], } ] try: # Send the message to the model, using a basic inference configuration. response = client.converse( modelId=model_id, messages=conversation, inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9}, ) # Extract and print the response text. response_text = response["output"]["message"]["content"][0]["text"] print(response_text) except (ClientError, Exception) as e: print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") exit(1)
  • Einzelheiten zur API finden Sie unter Converse in AWS SDK for Python (Boto3) API Reference.

Das folgende Codebeispiel zeigt, wie mithilfe der Invoke Model API eine Textnachricht an AI21 Labs Jurassic-2 gesendet wird.

SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Verwenden Sie die Invoke Model API, um eine Textnachricht zu senden.

# Use the native inference API to send a text message to AI21 Labs Jurassic-2. import boto3 import json from botocore.Exceptions import ClientError # Create a Bedrock Runtime client in the AWS Region of your choice. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Jurassic-2 Mid. model_id = "ai21.j2-mid-v1" # Define the prompt for the model. prompt = "Describe the purpose of a 'hello world' program in one line." # Format the request payload using the model's native structure. native_request = { "prompt": prompt, "maxTokens": 512, "temperature": 0.5, } # Convert the native request to JSON. request = json.dumps(native_request) try: # Invoke the model with the request. response = client.invoke_model(modelId=model_id, body=request) except (ClientError, Exception) as e: print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") exit(1) # Decode the response body. model_response = json.loads(response["body"].read()) # Extract and print the response text. response_text = model_response["completions"][0]["data"]["text"] print(response_text)
  • Einzelheiten zur API finden Sie InvokeModelin AWS SDK for Python (Boto3) API Reference.

Amazon Titan Image Generator

Das folgende Codebeispiel zeigt, wie Amazon Titan Image auf Amazon Bedrock aufgerufen wird, um ein Bild zu generieren.

SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Erstellen Sie ein Bild mit dem Amazon Titan Image Generator.

# Use the native inference API to create an image with Amazon Titan Image Generator import base64 import boto3 import json import os import random # Create a Bedrock Runtime client in the AWS Region of your choice. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Titan Image Generator G1. model_id = "amazon.titan-image-generator-v1" # Define the image generation prompt for the model. prompt = "A stylized picture of a cute old steampunk robot." # Generate a random seed. seed = random.randint(0, 2147483647) # Format the request payload using the model's native structure. native_request = { "taskType": "TEXT_IMAGE", "textToImageParams": {"text": prompt}, "imageGenerationConfig": { "numberOfImages": 1, "quality": "standard", "cfgScale": 8.0, "height": 512, "width": 512, "seed": seed, }, } # Convert the native request to JSON. request = json.dumps(native_request) # Invoke the model with the request. response = client.invoke_model(modelId=model_id, body=request) # Decode the response body. model_response = json.loads(response["body"].read()) # Extract the image data. base64_image_data = model_response["images"][0] # Save the generated image to a local folder. i, output_dir = 1, "output" if not os.path.exists(output_dir): os.makedirs(output_dir) while os.path.exists(os.path.join(output_dir, f"titan_{i}.png")): i += 1 image_data = base64.b64decode(base64_image_data) image_path = os.path.join(output_dir, f"titan_{i}.png") with open(image_path, "wb") as file: file.write(image_data) print(f"The generated image has been saved to {image_path}")
  • Einzelheiten zur API finden Sie InvokeModelin AWS SDK for Python (Boto3) API Reference.

Amazon Titan Text

Das folgende Codebeispiel zeigt, wie Sie mithilfe der Converse-API von Bedrock eine Textnachricht an Amazon Titan Text senden.

SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Senden Sie mithilfe der Converse-API von Bedrock eine Textnachricht an Amazon Titan Text.

# Use the Conversation API to send a text message to Amazon Titan Text. import boto3 from botocore.exceptions import ClientError # Create a Bedrock Runtime client in the AWS Region you want to use. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Titan Text Premier. model_id = "amazon.titan-text-premier-v1:0" # Start a conversation with the user message. user_message = "Describe the purpose of a 'hello world' program in one line." conversation = [ { "role": "user", "content": [{"text": user_message}], } ] try: # Send the message to the model, using a basic inference configuration. response = client.converse( modelId=model_id, messages=conversation, inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9}, ) # Extract and print the response text. response_text = response["output"]["message"]["content"][0]["text"] print(response_text) except (ClientError, Exception) as e: print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") exit(1)
  • Einzelheiten zur API finden Sie unter Converse in AWS SDK for Python (Boto3) API Reference.

Das folgende Codebeispiel zeigt, wie Sie mithilfe der Converse-API von Bedrock eine Textnachricht an Amazon Titan Text senden und den Antwortstream in Echtzeit verarbeiten.

SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Senden Sie mithilfe der Converse-API von Bedrock eine Textnachricht an Amazon Titan Text und verarbeiten Sie den Antwortstream in Echtzeit.

# Use the Conversation API to send a text message to Amazon Titan Text # and print the response stream. import boto3 from botocore.exceptions import ClientError # Create a Bedrock Runtime client in the AWS Region you want to use. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Titan Text Premier. model_id = "amazon.titan-text-premier-v1:0" # Start a conversation with the user message. user_message = "Describe the purpose of a 'hello world' program in one line." conversation = [ { "role": "user", "content": [{"text": user_message}], } ] try: # Send the message to the model, using a basic inference configuration. streaming_response = client.converse_stream( modelId=model_id, messages=conversation, inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9}, ) # Extract and print the streamed response text in real-time. for chunk in streaming_response["stream"]: if "contentBlockDelta" in chunk: text = chunk["contentBlockDelta"]["delta"]["text"] print(text, end="") except (ClientError, Exception) as e: print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") exit(1)
  • Einzelheiten zur API finden Sie ConverseStreamin AWS SDK for Python (Boto3) API Reference.

Das folgende Codebeispiel zeigt, wie Sie mithilfe der Invoke Model API eine Textnachricht an Amazon Titan Text senden.

SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Verwenden Sie die Invoke Model API, um eine Textnachricht zu senden.

# Use the native inference API to send a text message to Amazon Titan Text. import boto3 import json from botocore.Exceptions import ClientError # Create a Bedrock Runtime client in the AWS Region of your choice. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Titan Text Premier. model_id = "amazon.titan-text-premier-v1:0" # Define the prompt for the model. prompt = "Describe the purpose of a 'hello world' program in one line." # Format the request payload using the model's native structure. native_request = { "inputText": prompt, "textGenerationConfig": { "maxTokenCount": 512, "temperature": 0.5, }, } # Convert the native request to JSON. request = json.dumps(native_request) try: # Invoke the model with the request. response = client.invoke_model(modelId=model_id, body=request) except (ClientError, Exception) as e: print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") exit(1) # Decode the response body. model_response = json.loads(response["body"].read()) # Extract and print the response text. response_text = model_response["results"][0]["outputText"] print(response_text)
  • Einzelheiten zur API finden Sie InvokeModelin AWS SDK for Python (Boto3) API Reference.

Das folgende Codebeispiel zeigt, wie Sie mithilfe der Invoke Model API eine Textnachricht an Amazon Titan Text-Modelle senden und den Antwortstream drucken.

SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Verwenden Sie die Invoke Model API, um eine Textnachricht zu senden und den Antwortstream in Echtzeit zu verarbeiten.

# Use the native inference API to send a text message to Amazon Titan Text # and print the response stream. import boto3 import json # Create a Bedrock Runtime client in the AWS Region of your choice. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Titan Text Premier. model_id = "amazon.titan-text-premier-v1:0" # Define the prompt for the model. prompt = "Describe the purpose of a 'hello world' program in one line." # Format the request payload using the model's native structure. native_request = { "inputText": prompt, "textGenerationConfig": { "maxTokenCount": 512, "temperature": 0.5, }, } # Convert the native request to JSON. request = json.dumps(native_request) # Invoke the model with the request. streaming_response = client.invoke_model_with_response_stream( modelId=model_id, body=request ) # Extract and print the response text in real-time. for event in streaming_response["body"]: chunk = json.loads(event["chunk"]["bytes"]) if "outputText" in chunk: print(chunk["outputText"], end="")

Amazon Titan Text Embeddings

Wie das aussehen kann, sehen Sie am nachfolgenden Beispielcode:

  • Fangen Sie an, Ihre erste Einbettung zu erstellen.

  • Erstellen Sie Einbettungen, indem Sie die Anzahl der Dimensionen und die Normalisierung konfigurieren (nur V2).

SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Erstellen Sie Ihre erste Einbettung mit Amazon Titan Text Embeddings.

# Generate and print an embedding with Amazon Titan Text Embeddings V2. import boto3 import json # Create a Bedrock Runtime client in the AWS Region of your choice. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Titan Text Embeddings V2. model_id = "amazon.titan-embed-text-v2:0" # The text to convert to an embedding. input_text = "Please recommend books with a theme similar to the movie 'Inception'." # Create the request for the model. native_request = {"inputText": input_text} # Convert the native request to JSON. request = json.dumps(native_request) # Invoke the model with the request. response = client.invoke_model(modelId=model_id, body=request) # Decode the model's native response body. model_response = json.loads(response["body"].read()) # Extract and print the generated embedding and the input text token count. embedding = model_response["embedding"] input_token_count = model_response["inputTextTokenCount"] print("\nYour input:") print(input_text) print(f"Number of input tokens: {input_token_count}") print(f"Size of the generated embedding: {len(embedding)}") print("Embedding:") print(embedding)
  • Einzelheiten zur API finden Sie InvokeModelin AWS SDK for Python (Boto3) API Reference.

Anthropic Claude

Das folgende Codebeispiel zeigt, wie Sie mithilfe der Converse-API von Bedrock eine Textnachricht an Anthropic Claude senden.

SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Senden Sie mithilfe der Converse-API von Bedrock eine Textnachricht an Anthropic Claude.

# Use the Conversation API to send a text message to Anthropic Claude. import boto3 from botocore.exceptions import ClientError # Create a Bedrock Runtime client in the AWS Region you want to use. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Claude 3 Haiku. model_id = "anthropic.claude-3-haiku-20240307-v1:0" # Start a conversation with the user message. user_message = "Describe the purpose of a 'hello world' program in one line." conversation = [ { "role": "user", "content": [{"text": user_message}], } ] try: # Send the message to the model, using a basic inference configuration. response = client.converse( modelId=model_id, messages=conversation, inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9}, ) # Extract and print the response text. response_text = response["output"]["message"]["content"][0]["text"] print(response_text) except (ClientError, Exception) as e: print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") exit(1)
  • Einzelheiten zur API finden Sie unter Converse in AWS SDK for Python (Boto3) API Reference.

Das folgende Codebeispiel zeigt, wie Sie mithilfe der Converse-API von Bedrock eine Textnachricht an Anthropic Claude senden und den Antwortstream in Echtzeit verarbeiten.

SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Senden Sie mithilfe der Converse-API von Bedrock eine Textnachricht an Anthropic Claude und verarbeiten Sie den Antwortstream in Echtzeit.

# Use the Conversation API to send a text message to Anthropic Claude # and print the response stream. import boto3 from botocore.exceptions import ClientError # Create a Bedrock Runtime client in the AWS Region you want to use. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Claude 3 Haiku. model_id = "anthropic.claude-3-haiku-20240307-v1:0" # Start a conversation with the user message. user_message = "Describe the purpose of a 'hello world' program in one line." conversation = [ { "role": "user", "content": [{"text": user_message}], } ] try: # Send the message to the model, using a basic inference configuration. streaming_response = client.converse_stream( modelId=model_id, messages=conversation, inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9}, ) # Extract and print the streamed response text in real-time. for chunk in streaming_response["stream"]: if "contentBlockDelta" in chunk: text = chunk["contentBlockDelta"]["delta"]["text"] print(text, end="") except (ClientError, Exception) as e: print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") exit(1)
  • Einzelheiten zur API finden Sie ConverseStreamin AWS SDK for Python (Boto3) API Reference.

Das folgende Codebeispiel zeigt, wie mithilfe der Invoke Model API eine Textnachricht an Anthropic Claude gesendet wird.

SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Verwenden Sie die Invoke Model API, um eine Textnachricht zu senden.

# Use the native inference API to send a text message to Anthropic Claude. import boto3 import json from botocore.Exceptions import ClientError # Create a Bedrock Runtime client in the AWS Region of your choice. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Claude 3 Haiku. model_id = "anthropic.claude-3-haiku-20240307-v1:0" # Define the prompt for the model. prompt = "Describe the purpose of a 'hello world' program in one line." # Format the request payload using the model's native structure. native_request = { "anthropic_version": "bedrock-2023-05-31", "max_tokens": 512, "temperature": 0.5, "messages": [ { "role": "user", "content": [{"type": "text", "text": prompt}], } ], } # Convert the native request to JSON. request = json.dumps(native_request) try: # Invoke the model with the request. response = client.invoke_model(modelId=model_id, body=request) except (ClientError, Exception) as e: print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") exit(1) # Decode the response body. model_response = json.loads(response["body"].read()) # Extract and print the response text. response_text = model_response["content"][0]["text"] print(response_text)
  • Einzelheiten zur API finden Sie InvokeModelin AWS SDK for Python (Boto3) API Reference.

Das folgende Codebeispiel zeigt, wie mithilfe der Invoke Model API eine Textnachricht an Modelle von Anthropic Claude gesendet und der Antwortstream gedruckt wird.

SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Verwenden Sie die Invoke Model API, um eine Textnachricht zu senden und den Antwortstream in Echtzeit zu verarbeiten.

# Use the native inference API to send a text message to Anthropic Claude # and print the response stream. import boto3 import json # Create a Bedrock Runtime client in the AWS Region of your choice. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Claude 3 Haiku. model_id = "anthropic.claude-3-haiku-20240307-v1:0" # Define the prompt for the model. prompt = "Describe the purpose of a 'hello world' program in one line." # Format the request payload using the model's native structure. native_request = { "anthropic_version": "bedrock-2023-05-31", "max_tokens": 512, "temperature": 0.5, "messages": [ { "role": "user", "content": [{"type": "text", "text": prompt}], } ], } # Convert the native request to JSON. request = json.dumps(native_request) # Invoke the model with the request. streaming_response = client.invoke_model_with_response_stream( modelId=model_id, body=request ) # Extract and print the response text in real-time. for event in streaming_response["body"]: chunk = json.loads(event["chunk"]["bytes"]) if chunk["type"] == "content_block_delta": print(chunk["delta"].get("text", ""), end="")

Cohere Command

Das folgende Codebeispiel zeigt, wie mithilfe der Converse-API von Bedrock eine Textnachricht an Cohere Command gesendet wird.

SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Senden Sie mithilfe der Converse-API von Bedrock eine Textnachricht an Cohere Command.

# Use the Conversation API to send a text message to Cohere Command. import boto3 from botocore.exceptions import ClientError # Create a Bedrock Runtime client in the AWS Region you want to use. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Command R. model_id = "cohere.command-r-v1:0" # Start a conversation with the user message. user_message = "Describe the purpose of a 'hello world' program in one line." conversation = [ { "role": "user", "content": [{"text": user_message}], } ] try: # Send the message to the model, using a basic inference configuration. response = client.converse( modelId=model_id, messages=conversation, inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9}, ) # Extract and print the response text. response_text = response["output"]["message"]["content"][0]["text"] print(response_text) except (ClientError, Exception) as e: print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") exit(1)
  • Einzelheiten zur API finden Sie unter Converse in AWS SDK for Python (Boto3) API Reference.

Das folgende Codebeispiel zeigt, wie Sie mithilfe der Converse-API von Bedrock eine Textnachricht an Cohere Command senden und den Antwortstream in Echtzeit verarbeiten.

SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Senden Sie mithilfe der Converse-API von Bedrock eine Textnachricht an Cohere Command und verarbeiten Sie den Antwortstream in Echtzeit.

# Use the Conversation API to send a text message to Cohere Command # and print the response stream. import boto3 from botocore.exceptions import ClientError # Create a Bedrock Runtime client in the AWS Region you want to use. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Command R. model_id = "cohere.command-r-v1:0" # Start a conversation with the user message. user_message = "Describe the purpose of a 'hello world' program in one line." conversation = [ { "role": "user", "content": [{"text": user_message}], } ] try: # Send the message to the model, using a basic inference configuration. streaming_response = client.converse_stream( modelId=model_id, messages=conversation, inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9}, ) # Extract and print the streamed response text in real-time. for chunk in streaming_response["stream"]: if "contentBlockDelta" in chunk: text = chunk["contentBlockDelta"]["delta"]["text"] print(text, end="") except (ClientError, Exception) as e: print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") exit(1)
  • Einzelheiten zur API finden Sie ConverseStreamin AWS SDK for Python (Boto3) API Reference.

Das folgende Codebeispiel zeigt, wie mithilfe der Invoke Model API eine Textnachricht an Cohere Command R und R+ gesendet wird.

SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Verwenden Sie die Invoke Model API, um eine Textnachricht zu senden.

# Use the native inference API to send a text message to Cohere Command R and R+. import boto3 import json from botocore.Exceptions import ClientError # Create a Bedrock Runtime client in the AWS Region of your choice. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Command R. model_id = "cohere.command-r-v1:0" # Define the prompt for the model. prompt = "Describe the purpose of a 'hello world' program in one line." # Format the request payload using the model's native structure. native_request = { "message": prompt, "max_tokens": 512, "temperature": 0.5, } # Convert the native request to JSON. request = json.dumps(native_request) try: # Invoke the model with the request. response = client.invoke_model(modelId=model_id, body=request) except (ClientError, Exception) as e: print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") exit(1) # Decode the response body. model_response = json.loads(response["body"].read()) # Extract and print the response text. response_text = model_response["text"] print(response_text)
  • Einzelheiten zur API finden Sie InvokeModelin AWS SDK for Python (Boto3) API Reference.

Das folgende Codebeispiel zeigt, wie mithilfe der Invoke Model API eine Textnachricht an Cohere Command gesendet wird.

SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Verwenden Sie die Invoke Model API, um eine Textnachricht zu senden.

# Use the native inference API to send a text message to Cohere Command. import boto3 import json from botocore.Exceptions import ClientError # Create a Bedrock Runtime client in the AWS Region of your choice. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Command Light. model_id = "cohere.command-light-text-v14" # Define the prompt for the model. prompt = "Describe the purpose of a 'hello world' program in one line." # Format the request payload using the model's native structure. native_request = { "prompt": prompt, "max_tokens": 512, "temperature": 0.5, } # Convert the native request to JSON. request = json.dumps(native_request) try: # Invoke the model with the request. response = client.invoke_model(modelId=model_id, body=request) except (ClientError, Exception) as e: print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") exit(1) # Decode the response body. model_response = json.loads(response["body"].read()) # Extract and print the response text. response_text = model_response["generations"][0]["text"] print(response_text)
  • Einzelheiten zur API finden Sie InvokeModelin AWS SDK for Python (Boto3) API Reference.

Das folgende Codebeispiel zeigt, wie Sie mithilfe der Invoke Model API mit einem Antwortstream eine Textnachricht an Cohere Command senden.

SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Verwenden Sie die Invoke Model API, um eine Textnachricht zu senden und den Antwortstream in Echtzeit zu verarbeiten.

# Use the native inference API to send a text message to Cohere Command R and R+ # and print the response stream. import boto3 import json from botocore.Exceptions import ClientError # Create a Bedrock Runtime client in the AWS Region of your choice. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Command R. model_id = "cohere.command-r-v1:0" # Define the prompt for the model. prompt = "Describe the purpose of a 'hello world' program in one line." # Format the request payload using the model's native structure. native_request = { "message": prompt, "max_tokens": 512, "temperature": 0.5, } # Convert the native request to JSON. request = json.dumps(native_request) try: # Invoke the model with the request. streaming_response = client.invoke_model_with_response_stream( modelId=model_id, body=request ) # Extract and print the response text in real-time. for event in streaming_response["body"]: chunk = json.loads(event["chunk"]["bytes"]) if "generations" in chunk: print(chunk["generations"][0]["text"], end="") except (ClientError, Exception) as e: print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") exit(1)
  • Einzelheiten zur API finden Sie InvokeModelin AWS SDK for Python (Boto3) API Reference.

Das folgende Codebeispiel zeigt, wie Sie mithilfe der Invoke Model API mit einem Antwortstream eine Textnachricht an Cohere Command senden.

SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Verwenden Sie die Invoke Model API, um eine Textnachricht zu senden und den Antwortstream in Echtzeit zu verarbeiten.

# Use the native inference API to send a text message to Cohere Command # and print the response stream. import boto3 import json from botocore.Exceptions import ClientError # Create a Bedrock Runtime client in the AWS Region of your choice. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Command Light. model_id = "cohere.command-light-text-v14" # Define the prompt for the model. prompt = "Describe the purpose of a 'hello world' program in one line." # Format the request payload using the model's native structure. native_request = { "prompt": prompt, "max_tokens": 512, "temperature": 0.5, } # Convert the native request to JSON. request = json.dumps(native_request) try: # Invoke the model with the request. streaming_response = client.invoke_model_with_response_stream( modelId=model_id, body=request ) # Extract and print the response text in real-time. for event in streaming_response["body"]: chunk = json.loads(event["chunk"]["bytes"]) if "generations" in chunk: print(chunk["generations"][0]["text"], end="") except (ClientError, Exception) as e: print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") exit(1)
  • Einzelheiten zur API finden Sie InvokeModelin AWS SDK for Python (Boto3) API Reference.

Meta-Lama

Das folgende Codebeispiel zeigt, wie Sie mithilfe der Converse-API von Bedrock eine Textnachricht an Meta Llama senden.

SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Senden Sie mithilfe der Converse-API von Bedrock eine Textnachricht an Meta Llama.

# Use the Conversation API to send a text message to Meta Llama. import boto3 from botocore.exceptions import ClientError # Create a Bedrock Runtime client in the AWS Region you want to use. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Llama 3 8b Instruct. model_id = "meta.llama3-8b-instruct-v1:0" # Start a conversation with the user message. user_message = "Describe the purpose of a 'hello world' program in one line." conversation = [ { "role": "user", "content": [{"text": user_message}], } ] try: # Send the message to the model, using a basic inference configuration. response = client.converse( modelId=model_id, messages=conversation, inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9}, ) # Extract and print the response text. response_text = response["output"]["message"]["content"][0]["text"] print(response_text) except (ClientError, Exception) as e: print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") exit(1)
  • Einzelheiten zur API finden Sie unter Converse in AWS SDK for Python (Boto3) API Reference.

Das folgende Codebeispiel zeigt, wie Sie mithilfe der Converse-API von Bedrock eine Textnachricht an Meta Llama senden und den Antwortstream in Echtzeit verarbeiten.

SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Senden Sie mithilfe der Converse-API von Bedrock eine Textnachricht an Meta Llama und verarbeiten Sie den Antwortstream in Echtzeit.

# Use the Conversation API to send a text message to Meta Llama # and print the response stream. import boto3 from botocore.exceptions import ClientError # Create a Bedrock Runtime client in the AWS Region you want to use. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Llama 3 8b Instruct. model_id = "meta.llama3-8b-instruct-v1:0" # Start a conversation with the user message. user_message = "Describe the purpose of a 'hello world' program in one line." conversation = [ { "role": "user", "content": [{"text": user_message}], } ] try: # Send the message to the model, using a basic inference configuration. streaming_response = client.converse_stream( modelId=model_id, messages=conversation, inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9}, ) # Extract and print the streamed response text in real-time. for chunk in streaming_response["stream"]: if "contentBlockDelta" in chunk: text = chunk["contentBlockDelta"]["delta"]["text"] print(text, end="") except (ClientError, Exception) as e: print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") exit(1)
  • Einzelheiten zur API finden Sie ConverseStreamin AWS SDK for Python (Boto3) API Reference.

Das folgende Codebeispiel zeigt, wie mithilfe der Invoke Model API eine Textnachricht an Meta Llama 2 gesendet wird.

SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Verwenden Sie die Invoke Model API, um eine Textnachricht zu senden.

# Use the native inference API to send a text message to Meta Llama 2. import boto3 import json from botocore.Exceptions import ClientError # Create a Bedrock Runtime client in the AWS Region of your choice. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Llama 2 Chat 13B. model_id = "meta.llama2-13b-chat-v1" # Define the prompt for the model. prompt = "Describe the purpose of a 'hello world' program in one line." # Embed the prompt in Llama 2's instruction format. formatted_prompt = f"<s>[INST] {prompt} [/INST]" # Format the request payload using the model's native structure. native_request = { "prompt": formatted_prompt, "max_gen_len": 512, "temperature": 0.5, } # Convert the native request to JSON. request = json.dumps(native_request) try: # Invoke the model with the request. response = client.invoke_model(modelId=model_id, body=request) except (ClientError, Exception) as e: print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") exit(1) # Decode the response body. model_response = json.loads(response["body"].read()) # Extract and print the response text. response_text = model_response["generation"] print(response_text)
  • Einzelheiten zur API finden Sie InvokeModelin AWS SDK for Python (Boto3) API Reference.

Das folgende Codebeispiel zeigt, wie mithilfe der Invoke Model API eine Textnachricht an Meta Llama 3 gesendet wird.

SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Verwenden Sie die Invoke Model API, um eine Textnachricht zu senden.

# Use the native inference API to send a text message to Meta Llama 3. import boto3 import json from botocore.Exceptions import ClientError # Create a Bedrock Runtime client in the AWS Region of your choice. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Llama 3 8b Instruct. model_id = "meta.llama3-8b-instruct-v1:0" # Define the prompt for the model. prompt = "Describe the purpose of a 'hello world' program in one line." # Embed the prompt in Llama 3's instruction format. formatted_prompt = f""" <|begin_of_text|> <|start_header_id|>user<|end_header_id|> {prompt} <|eot_id|> <|start_header_id|>assistant<|end_header_id|> """ # Format the request payload using the model's native structure. native_request = { "prompt": formatted_prompt, "max_gen_len": 512, "temperature": 0.5, } # Convert the native request to JSON. request = json.dumps(native_request) try: # Invoke the model with the request. response = client.invoke_model(modelId=model_id, body=request) except (ClientError, Exception) as e: print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") exit(1) # Decode the response body. model_response = json.loads(response["body"].read()) # Extract and print the response text. response_text = model_response["generation"] print(response_text)
  • Einzelheiten zur API finden Sie InvokeModelin AWS SDK for Python (Boto3) API Reference.

Das folgende Codebeispiel zeigt, wie Sie mithilfe der Invoke Model API eine Textnachricht an Meta Llama 2 senden und den Antwortstream drucken.

SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Verwenden Sie die Invoke Model API, um eine Textnachricht zu senden und den Antwortstream in Echtzeit zu verarbeiten.

# Use the native inference API to send a text message to Meta Llama 2 # and print the response stream. import boto3 import json from botocore.Exceptions import ClientError # Create a Bedrock Runtime client in the AWS Region of your choice. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Llama 2 Chat 13B. model_id = "meta.llama2-13b-chat-v1" # Define the prompt for the model. prompt = "Describe the purpose of a 'hello world' program in one line." # Embed the prompt in Llama 2's instruction format. formatted_prompt = f"<s>[INST] {prompt} [/INST]" # Format the request payload using the model's native structure. native_request = { "prompt": formatted_prompt, "max_gen_len": 512, "temperature": 0.5, } # Convert the native request to JSON. request = json.dumps(native_request) try: # Invoke the model with the request. streaming_response = client.invoke_model_with_response_stream( modelId=model_id, body=request ) # Extract and print the response text in real-time. for event in streaming_response["body"]: chunk = json.loads(event["chunk"]["bytes"]) if "generation" in chunk: print(chunk["generation"], end="") except (ClientError, Exception) as e: print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") exit(1)

Das folgende Codebeispiel zeigt, wie Sie mithilfe der Invoke Model API eine Textnachricht an Meta Llama 3 senden und den Antwortstream drucken.

SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Verwenden Sie die Invoke Model API, um eine Textnachricht zu senden und den Antwortstream in Echtzeit zu verarbeiten.

# Use the native inference API to send a text message to Meta Llama 3 # and print the response stream. import boto3 import json from botocore.Exceptions import ClientError # Create a Bedrock Runtime client in the AWS Region of your choice. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Llama 3 8b Instruct. model_id = "meta.llama3-8b-instruct-v1:0" # Define the prompt for the model. prompt = "Describe the purpose of a 'hello world' program in one line." # Embed the prompt in Llama 3's instruction format. formatted_prompt = f""" <|begin_of_text|> <|start_header_id|>user<|end_header_id|> {prompt} <|eot_id|> <|start_header_id|>assistant<|end_header_id|> """ # Format the request payload using the model's native structure. native_request = { "prompt": formatted_prompt, "max_gen_len": 512, "temperature": 0.5, } # Convert the native request to JSON. request = json.dumps(native_request) try: # Invoke the model with the request. streaming_response = client.invoke_model_with_response_stream( modelId=model_id, body=request ) # Extract and print the response text in real-time. for event in streaming_response["body"]: chunk = json.loads(event["chunk"]["bytes"]) if "generation" in chunk: print(chunk["generation"], end="") except (ClientError, Exception) as e: print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") exit(1)

Mistral KI

Das folgende Codebeispiel zeigt, wie Sie mithilfe der Converse-API von Bedrock eine Textnachricht an Mistral senden.

SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Senden Sie mithilfe der Converse-API von Bedrock eine Textnachricht an Mistral.

# Use the Conversation API to send a text message to Mistral. import boto3 from botocore.exceptions import ClientError # Create a Bedrock Runtime client in the AWS Region you want to use. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Mistral Large. model_id = "mistral.mistral-large-2402-v1:0" # Start a conversation with the user message. user_message = "Describe the purpose of a 'hello world' program in one line." conversation = [ { "role": "user", "content": [{"text": user_message}], } ] try: # Send the message to the model, using a basic inference configuration. response = client.converse( modelId=model_id, messages=conversation, inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9}, ) # Extract and print the response text. response_text = response["output"]["message"]["content"][0]["text"] print(response_text) except (ClientError, Exception) as e: print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") exit(1)
  • Einzelheiten zur API finden Sie unter Converse in AWS SDK for Python (Boto3) API Reference.

Das folgende Codebeispiel zeigt, wie Sie mithilfe der Converse-API von Bedrock eine Textnachricht an Mistral senden und den Antwortstream in Echtzeit verarbeiten.

SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Senden Sie mithilfe der Converse-API von Bedrock eine Textnachricht an Mistral und verarbeiten Sie den Antwortstream in Echtzeit.

# Use the Conversation API to send a text message to Mistral # and print the response stream. import boto3 from botocore.exceptions import ClientError # Create a Bedrock Runtime client in the AWS Region you want to use. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Mistral Large. model_id = "mistral.mistral-large-2402-v1:0" # Start a conversation with the user message. user_message = "Describe the purpose of a 'hello world' program in one line." conversation = [ { "role": "user", "content": [{"text": user_message}], } ] try: # Send the message to the model, using a basic inference configuration. streaming_response = client.converse_stream( modelId=model_id, messages=conversation, inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9}, ) # Extract and print the streamed response text in real-time. for chunk in streaming_response["stream"]: if "contentBlockDelta" in chunk: text = chunk["contentBlockDelta"]["delta"]["text"] print(text, end="") except (ClientError, Exception) as e: print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") exit(1)
  • Einzelheiten zur API finden Sie ConverseStreamin AWS SDK for Python (Boto3) API Reference.

Das folgende Codebeispiel zeigt, wie mithilfe der Invoke Model API eine Textnachricht an Mistral-Modelle gesendet wird.

SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Verwenden Sie die Invoke Model API, um eine Textnachricht zu senden.

# Use the native inference API to send a text message to Mistral. import boto3 import json from botocore.Exceptions import ClientError # Create a Bedrock Runtime client in the AWS Region of your choice. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Mistral Large. model_id = "mistral.mistral-large-2402-v1:0" # Define the prompt for the model. prompt = "Describe the purpose of a 'hello world' program in one line." # Embed the prompt in Mistral's instruction format. formatted_prompt = f"<s>[INST] {prompt} [/INST]" # Format the request payload using the model's native structure. native_request = { "prompt": formatted_prompt, "max_tokens": 512, "temperature": 0.5, } # Convert the native request to JSON. request = json.dumps(native_request) try: # Invoke the model with the request. response = client.invoke_model(modelId=model_id, body=request) except (ClientError, Exception) as e: print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") exit(1) # Decode the response body. model_response = json.loads(response["body"].read()) # Extract and print the response text. response_text = model_response["outputs"][0]["text"] print(response_text)
  • Einzelheiten zur API finden Sie InvokeModelin AWS SDK for Python (Boto3) API Reference.

Das folgende Codebeispiel zeigt, wie Sie mithilfe der Invoke Model API eine Textnachricht an Mistral AI-Modelle senden und den Antwortstream drucken.

SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Verwenden Sie die Invoke Model API, um eine Textnachricht zu senden und den Antwortstream in Echtzeit zu verarbeiten.

# Use the native inference API to send a text message to Mistral # and print the response stream. import boto3 import json from botocore.Exceptions import ClientError # Create a Bedrock Runtime client in the AWS Region of your choice. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Mistral Large. model_id = "mistral.mistral-large-2402-v1:0" # Define the prompt for the model. prompt = "Describe the purpose of a 'hello world' program in one line." # Embed the prompt in Mistral's instruction format. formatted_prompt = f"<s>[INST] {prompt} [/INST]" # Format the request payload using the model's native structure. native_request = { "prompt": formatted_prompt, "max_tokens": 512, "temperature": 0.5, } # Convert the native request to JSON. request = json.dumps(native_request) try: # Invoke the model with the request. streaming_response = client.invoke_model_with_response_stream( modelId=model_id, body=request ) # Extract and print the response text in real-time. for event in streaming_response["body"]: chunk = json.loads(event["chunk"]["bytes"]) if "outputs" in chunk: print(chunk["outputs"][0].get("text"), end="") except (ClientError, Exception) as e: print(f"ERROR: Can't invoke '{model_id}''. Reason: {e}") exit(1)

Szenarien

Das folgende Codebeispiel zeigt, wie Spielplätze für die Interaktion mit Amazon Bedrock Foundation-Modellen über verschiedene Modalitäten erstellt werden.

SDK für Python (Boto3)

Der Python Foundation Model (FM) Playground ist eine Python/FastAPI-Beispielanwendung, die zeigt, wie Amazon Bedrock mit Python verwendet wird. Dieses Beispiel zeigt, wie Python-Entwickler Amazon Bedrock verwenden können, um generative KI-fähige Anwendungen zu erstellen. Sie können Amazon Bedrock Foundation-Modelle testen und mit ihnen interagieren, indem Sie die folgenden drei Playgrounds verwenden:

  • Eine Spielwiese mit Text.

  • Ein Chat-Spielplatz.

  • Ein Spielplatz mit Bildern.

In dem Beispiel werden auch die Fundamentmodelle, auf die Sie Zugriff haben, zusammen mit ihren Eigenschaften aufgelistet und angezeigt. Quellcode und Anweisungen zur Bereitstellung finden Sie im Projekt unter GitHub.

In diesem Beispiel verwendete Dienste
  • Amazon Bedrock Runtime

Das folgende Codebeispiel zeigt, wie generative KI-Anwendungen mit Amazon Bedrock und Step Functions erstellt und orchestriert werden.

SDK für Python (Boto3)

Das Szenario Amazon Bedrock Serverless Prompt Chaining zeigt AWS Step Functions, wie Amazon Bedrock und Agents for Amazon Bedrock verwendet werden können, um komplexe, serverlose und hoch skalierbare generative KI-Anwendungen zu erstellen und zu orchestrieren. Es enthält die folgenden Arbeitsbeispiele:

  • Schreiben Sie eine Analyse eines bestimmten Romans für einen Literatur-Blog. Dieses Beispiel veranschaulicht eine einfache, sequentielle Kette von Eingabeaufforderungen.

  • Generieren Sie eine Kurzgeschichte zu einem bestimmten Thema. Dieses Beispiel zeigt, wie die KI eine zuvor generierte Liste von Elementen iterativ verarbeiten kann.

  • Erstellen Sie eine Reiseroute für einen Wochenendurlaub zu einem bestimmten Ziel. Dieses Beispiel zeigt, wie mehrere unterschiedliche Eingabeaufforderungen parallelisiert werden.

  • Präsentieren Sie Filmideen einem menschlichen Benutzer, der als Filmproduzent fungiert. Dieses Beispiel zeigt, wie dieselbe Aufforderung mit unterschiedlichen Inferenzparametern parallelisiert wird, wie man zu einem vorherigen Schritt in der Kette zurückkehrt und wie menschliche Eingaben in den Arbeitsablauf einbezogen werden können.

  • Planen Sie eine Mahlzeit auf der Grundlage der Zutaten, die der Benutzer zur Hand hat. Dieses Beispiel zeigt, wie Prompt-Chains zwei unterschiedliche KI-Konversationen beinhalten können, bei denen zwei KI-Personas miteinander debattieren, um das Endergebnis zu verbessern.

  • Finden Sie das Archiv mit den meisten Trends GitHub von heute und fassen Sie es zusammen. Dieses Beispiel veranschaulicht die Verkettung mehrerer KI-Agenten, die mit externen APIs interagieren.

Den vollständigen Quellcode und Anweisungen zur Einrichtung und Ausführung finden Sie im vollständigen Projekt unter GitHub.

In diesem Beispiel verwendete Dienste
  • Amazon Bedrock

  • Amazon Bedrock Runtime

  • Agents für Amazon Bedrock

  • Agenten für Amazon Bedrock Runtime

  • Step Functions

Stabile Diffusion

Das folgende Codebeispiel zeigt, wie Stability.ai Stable Diffusion XL auf Amazon Bedrock aufgerufen wird, um ein Bild zu generieren.

SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Erstellen Sie ein Bild mit Stable Diffusion.

# Use the native inference API to create an image with Stability.ai Stable Diffusion import base64 import boto3 import json import os import random # Create a Bedrock Runtime client in the AWS Region of your choice. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Stable Diffusion XL 1. model_id = "stability.stable-diffusion-xl-v1" # Define the image generation prompt for the model. prompt = "A stylized picture of a cute old steampunk robot." # Generate a random seed. seed = random.randint(0, 4294967295) # Format the request payload using the model's native structure. native_request = { "text_prompts": [{"text": prompt}], "style_preset": "photographic", "seed": seed, "cfg_scale": 10, "steps": 30, } # Convert the native request to JSON. request = json.dumps(native_request) # Invoke the model with the request. response = client.invoke_model(modelId=model_id, body=request) # Decode the response body. model_response = json.loads(response["body"].read()) # Extract the image data. base64_image_data = model_response["artifacts"][0]["base64"] # Save the generated image to a local folder. i, output_dir = 1, "output" if not os.path.exists(output_dir): os.makedirs(output_dir) while os.path.exists(os.path.join(output_dir, f"stability_{i}.png")): i += 1 image_data = base64.b64decode(base64_image_data) image_path = os.path.join(output_dir, f"stability_{i}.png") with open(image_path, "wb") as file: file.write(image_data) print(f"The generated image has been saved to {image_path}")
  • Einzelheiten zur API finden Sie InvokeModelin AWS SDK for Python (Boto3) API Reference.