Aws Sdk Java V2 Bedrock logo

Aws Sdk Java V2 Bedrock

Community
giuseppe-trisciuoglio
aws-sdk-java-v2-bedrock

Provides Amazon Bedrock patterns using AWS SDK for Java 2.x. Invokes foundation models (Claude, Llama, Titan), generates text and images, creates embeddings for RAG, streams real-time responses, and configures Spring Boot integration. Use when asking about Bedrock integration, Java SDK for AI models, AWS generative AI, Claude/Llama invocation, embeddings for RAG, or Spring Boot AI setup.

Overview

Publishergiuseppe-trisciuoglio
Repositorydeveloper-kit
Skill nameaws-sdk-java-v2-bedrock
Stars
345
Forks
41
Bundled files
12
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • 12 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • Open source

    Published by giuseppe-trisciuoglio on GitHub. Read the source before you install it.

Installation

Install the Aws Sdk Java V2 Bedrock AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/giuseppe-trisciuoglio/developer-kit.git /tmp/developer-kit
mkdir -p .claude/skills
cp -r /tmp/developer-kit/plugins/developer-kit-java/skills/aws-sdk-java-v2-bedrock .claude/skills/aws-sdk-java-v2-bedrock
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Aws Sdk Java V2 Bedrock in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Aws Sdk Java V2 Bedrock on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Aws Sdk Java V2 Bedrock is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

AWS SDK for Java 2.x - Amazon Bedrock

Overview

Invokes foundation models through AWS SDK for Java 2.x. Configures clients, builds model-specific JSON payloads, handles streaming responses with error recovery, creates embeddings for RAG, integrates generative AI into Spring Boot applications, and implements exponential backoff for resilience.

When to Use

  • Invoke Claude, Llama, Titan, or Stable Diffusion for text/image generation
  • Configure BedrockClient and BedrockRuntimeClient instances
  • Build and parse model-specific payloads (Claude, Titan, Llama formats)
  • Stream real-time AI responses with async handlers and error recovery
  • Create embeddings for retrieval-augmented generation
  • Integrate generative AI into Spring Boot microservices
  • Handle throttling with exponential backoff retry logic

Quick Start

Dependencies

xml
<!-- Bedrock (model management) -->
<dependency>
    <groupId>software.amazon.awssdk</groupId>
    <artifactId>bedrock</artifactId>
</dependency>

<!-- Bedrock Runtime (model invocation) -->
<dependency>
    <groupId>software.amazon.awssdk</groupId>
    <artifactId>bedrockruntime</artifactId>
</dependency>

<!-- For JSON processing -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20231013</version>
</dependency>

Client Setup

java
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrock.BedrockClient;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;

// Model management client
BedrockClient bedrockClient = BedrockClient.builder()
    .region(Region.US_EAST_1)
    .build();

// Model invocation client
BedrockRuntimeClient bedrockRuntimeClient = BedrockRuntimeClient.builder()
    .region(Region.US_EAST_1)
    .build();

Instructions

Follow these steps for production-ready Bedrock integration:

  1. Configure AWS Credentials - Set up IAM roles with Bedrock permissions (avoid access keys)
  2. Enable Model Access - Request access to specific foundation models in AWS Console
  3. Initialize Clients - Create reusable BedrockClient and BedrockRuntimeClient instances
  4. Validate Model Availability - Test with a simple invocation before production use
  5. Build Payloads - Create model-specific JSON payloads with proper format
  6. Handle Responses - Parse response structure and extract content
  7. Implement Streaming - Use response stream handlers for real-time generation
  8. Add Error Handling - Implement retry logic with exponential backoff

Validation Checkpoint: Always test with a simple prompt (e.g., "Hello") before production use to verify model access and response parsing.

Examples

Text Generation with Claude

java
public String generateWithClaude(BedrockRuntimeClient client, String prompt) {
    JSONObject payload = new JSONObject()
        .put("anthropic_version", "bedrock-2023-05-31")
        .put("max_tokens", 1000)
        .put("messages", new JSONObject[]{
            new JSONObject().put("role", "user").put("content", prompt)
        });

    InvokeModelResponse response = client.invokeModel(InvokeModelRequest.builder()
        .modelId("anthropic.claude-sonnet-4-5-20250929-v1:0")
        .body(SdkBytes.fromUtf8String(payload.toString()))
        .build());

    JSONObject responseBody = new JSONObject(response.body().asUtf8String());
    return responseBody.getJSONArray("content")
        .getJSONObject(0)
        .getString("text");
}

Model Discovery

java
import software.amazon.awssdk.services.bedrock.model.*;

public List<FoundationModelSummary> listFoundationModels(BedrockClient bedrockClient) {
    return bedrockClient.listFoundationModels().modelSummaries();
}

Multi-Model Invocation

java
public String invokeModel(BedrockRuntimeClient client, String modelId, String prompt) {
    JSONObject payload = createPayload(modelId, prompt);

    InvokeModelResponse response = client.invokeModel(request -> request
        .modelId(modelId)
        .body(SdkBytes.fromUtf8String(payload.toString())));

    return extractTextFromResponse(modelId, response.body().asUtf8String());
}

private JSONObject createPayload(String modelId, String prompt) {
    if (modelId.startsWith("anthropic.claude")) {
        return new JSONObject()
            .put("anthropic_version", "bedrock-2023-05-31")
            .put("max_tokens", 1000)
            .put("messages", new JSONObject[]{
                new JSONObject().put("role", "user").put("content", prompt)
            });
    } else if (modelId.startsWith("amazon.titan")) {
        return new JSONObject()
            .put("inputText", prompt)
            .put("textGenerationConfig", new JSONObject()
                .put("maxTokenCount", 512)
                .put("temperature", 0.7));
    } else if (modelId.startsWith("meta.llama")) {
        return new JSONObject()
            .put("prompt", "[INST] " + prompt + " [/INST]")
            .put("max_gen_len", 512)
            .put("temperature", 0.7);
    }
    throw new IllegalArgumentException("Unsupported model: " + modelId);
}

Streaming Response with Error Handling

java
public String streamResponseWithRetry(BedrockRuntimeClient client, String modelId, String prompt, int maxRetries) {
    int attempt = 0;
    while (attempt < maxRetries) {
        try {
            JSONObject payload = createPayload(modelId, prompt);
            StringBuilder fullResponse = new StringBuilder();

            InvokeModelWithResponseStreamRequest request = InvokeModelWithResponseStreamRequest.builder()
                .modelId(modelId)
                .body(SdkBytes.fromUtf8String(payload.toString()))
                .build();

            client.invokeModelWithResponseStream(request,
                InvokeModelWithResponseStreamResponseHandler.builder()
                    .onEventStream(stream -> stream.forEach(event -> {
                        if (event instanceof PayloadPart) {
                            String chunk = ((PayloadPart) event).bytes().asUtf8String();
                            fullResponse.append(chunk);
                        }
                    }))
                    .onError(e -> System.err.println("Stream error: " + e.getMessage()))
                    .build());

            return fullResponse.toString();
        } catch (Exception e) {
            attempt++;
            if (attempt >= maxRetries) {
                throw new RuntimeException("Stream failed after " + maxRetries + " attempts", e);
            }
            try {
                Thread.sleep((long) Math.pow(2, attempt) * 1000); // Exponential backoff
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
                throw new RuntimeException("Interrupted during retry", ie);
            }
        }
    }
    throw new RuntimeException("Unexpected error in streaming");
}

Exponential Backoff for Throttling

java
import software.amazon.awssdk.awscore.exception.AwsServiceException;

public <T> T invokeWithRetry(Supplier<T> invocation, int maxRetries) {
    int attempt = 0;
    while (attempt < maxRetries) {
        try {
            return invocation.get();
        } catch (AwsServiceException e) {
            if (e.statusCode() == 429 || e.statusCode() >= 500) {
                attempt++;
                if (attempt >= maxRetries) throw e;
                long delayMs = Math.min(1000 * (1L << attempt) + (long) (Math.random() * 1000), 30000);
                Thread.sleep(delayMs);
            } else {
                throw e;
            }
        }
    }
    throw new IllegalStateException("Should not reach here");
}

Text Embeddings

java
public double[] createEmbeddings(BedrockRuntimeClient client, String text) {
    String modelId = "amazon.titan-embed-text-v1";

    JSONObject payload = new JSONObject().put("inputText", text);

    InvokeModelResponse response = client.invokeModel(request -> request
        .modelId(modelId)
        .body(SdkBytes.fromUtf8String(payload.toString())));

    JSONObject responseBody = new JSONObject(response.body().asUtf8String());
    JSONArray embeddingArray = responseBody.getJSONArray("embedding");

    double[] embeddings = new double[embeddingArray.length()];
    for (int i = 0; i < embeddingArray.length(); i++) {
        embeddings[i] = embeddingArray.getDouble(i);
    }
    return embeddings;
}

Spring Boot Integration

java
@Configuration
public class BedrockConfiguration {

    @Bean
    public BedrockClient bedrockClient() {
        return BedrockClient.builder()
            .region(Region.US_EAST_1)
            .build();
    }

    @Bean
    public BedrockRuntimeClient bedrockRuntimeClient() {
        return BedrockRuntimeClient.builder()
            .region(Region.US_EAST_1)
            .build();
    }
}

@Service
public class BedrockAIService {

    private final BedrockRuntimeClient bedrockRuntimeClient;
    private final ObjectMapper mapper;

    @Value("${bedrock.default-model-id:anthropic.claude-sonnet-4-5-20250929-v1:0}")
    private String defaultModelId;

    public BedrockAIService(BedrockRuntimeClient bedrockRuntimeClient, ObjectMapper mapper) {
        this.bedrockRuntimeClient = bedrockRuntimeClient;
        this.mapper = mapper;
    }

    public String generateText(String prompt) {
        Map<String, Object> payload = Map.of(
            "anthropic_version", "bedrock-2023-05-31",
            "max_tokens", 1000,
            "messages", List.of(Map.of("role", "user", "content", prompt))
        );

        InvokeModelResponse response = bedrockRuntimeClient.invokeModel(
            InvokeModelRequest.builder()
                .modelId(defaultModelId)
                .body(SdkBytes.fromUtf8String(mapper.writeValueAsString(payload)))
                .build());

        return extractText(response.body().asUtf8String());
    }
}

See examples directory for comprehensive usage patterns.

Best Practices

Model Selection

  • Claude 4.5 Sonnet: Complex reasoning, analysis, and creative tasks
  • Claude 4.5 Haiku: Fast and affordable for real-time applications
  • Llama 3.1: Open-source alternative for general tasks
  • Titan: AWS native, cost-effective for simple text generation

Performance

  • Reuse client instances (avoid creating new clients per request)
  • Use async clients for I/O operations
  • Implement streaming for long responses
  • Cache foundation model lists

Security

  • Never log sensitive prompt data
  • Use IAM roles for authentication
  • Sanitize user inputs to prevent prompt injection
  • Implement rate limiting for public applications

Constraints and Warnings

  • Cost Management: Bedrock API calls incur charges per token; implement usage monitoring and budget alerts.
  • Model Access: Foundation models must be enabled in AWS Console; verify region availability.
  • Rate Limits: Implement exponential backoff for throttling; check per-model limits.
  • Payload Size: Maximum payload size varies by model; use chunking for large documents.
  • Streaming Complexity: Handle partial content and error recovery carefully.
  • Data Privacy: Prompts and responses may be logged by AWS; review data policies.
  • Credentials: Never embed credentials in code; use IAM roles for EC2/Lambda.

Common Model IDs

  • Claude Sonnet 4.5: anthropic.claude-sonnet-4-5-20250929-v1:0
  • Claude Haiku 4.5: anthropic.claude-haiku-4-5-20251001-v1:0
  • Llama 3.1 70B: meta.llama3-1-70b-instruct-v1:0
  • Titan Embeddings: amazon.titan-embed-text-v1

See Model Reference for complete list.

References

Related Skills

  • aws-sdk-java-v2-core - Core AWS SDK patterns
  • langchain4j-ai-services-patterns - LangChain4j integration
  • spring-boot-dependency-injection - Spring DI patterns

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

Frequently asked questions

What does the Aws Sdk Java V2 Bedrock AI skill do?

Provides Amazon Bedrock patterns using AWS SDK for Java 2.x. Invokes foundation models (Claude, Llama, Titan), generates text and images, creates embeddings for RAG, streams real-time responses, and configures Spring Boot integration. Use when asking about Bedrock integration, Java SDK for AI models, AWS generative AI, Claude/Llama invocation, embeddings for RAG, or Spring Boot AI setup.

Why use Aws Sdk Java V2 Bedrock on TypingMind?

Because you install it once and use it with any model. Aws Sdk Java V2 Bedrock is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Aws Sdk Java V2 Bedrock in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/giuseppe-trisciuoglio/developer-kit/tree/main/plugins/developer-kit-java/skills/aws-sdk-java-v2-bedrock. TypingMind reads its SKILL.md and bundles its files and installs it as a skill you can enable per chat.

Which AI models can use Aws Sdk Java V2 Bedrock?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Aws Sdk Java V2 Bedrock?

As many as you like. As long as a model supports skills, you can use Aws Sdk Java V2 Bedrock with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Aws Sdk Java V2 Bedrock AI skill free?

Yes. It is published on GitHub by giuseppe-trisciuoglio under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇