How do you use AWS Bedrock Converse API to standardize payloads across Claude, Llama, and Mistral models? | A1Lab@HamzaM to AI & LLMEnglish • 3 days ago

How do you use AWS Bedrock Converse API to standardize payloads across Claude, Llama, and Mistral models?

message-square
0

How AWS Bedrock Converse API Standardizes Claude, Llama, and Mistral Payloads

Using InvokeModel directly forces you to maintain separate request schemas and response parsers for each provider—for example, anthropic_version and content blocks for Claude, or distinct prompt/parameter shapes for Meta Llama and Mistral. The Amazon Bedrock Converse API (Converse and ConverseStream on BedrockRuntimeClient) provides a single normalized message envelope, inference configuration, tool-use schema, and response structure across all chat models that support messages.

  • Unified message and content-block format: Every turn uses messages with role ("user" or "assistant") and an array of typed ContentBlock objects ({ text }, { image }, { document }, { toolUse }, { toolResult }), while system instructions live in the top-level system parameter ([{ text: "..." }]) rather than provider-specific fields.
  • Normalized inference parameters and response envelope: Common controls such as maxTokens, temperature, topP, and stopSequences sit inside inferenceConfig, and responses return a consistent output.message, stopReason ("end_turn", "tool_use", "max_tokens"), usage, and metrics shape regardless of whether you target Claude, Llama, or Mistral.
  • Model-specific escape hatch (additionalModelRequestFields): When a parameter is unique to one model family (such as top_k or reasoning/thinking options), you can pass provider-specific fields via additionalModelRequestFields without breaking the common messages and inferenceConfig contract.

Steps to Standardize Multi-Model Calls with Bedrock Converse

  1. Swap modelId (or inference profile) without rewriting payloads: Keep one canonical Message[], system, inferenceConfig, and toolConfig builder in your orchestration layer and route dynamically across Anthropic Claude, Meta Llama, and Mistral model IDs or cross-region inference profiles.
  2. Use toolConfig with toolSpec.inputSchema.json for function calling: Define tools once in toolConfig, append the assistant’s output.message containing toolUse blocks back to messages, execute the tool, and return a user message containing { toolResult: { toolUseId, content } }.
  3. Use ConverseStreamCommand for real-time streaming: Stream contentBlockDelta events for text or tool input JSON and read messageStop / metadata for stopReason and token counts using the same request structure.
  4. Guard against per-model feature differences: Verify model-level support in your target AWS Region for features like tool calling, vision/document blocks, or system prompts before routing traffic dynamically.

TypeScript Example: Unified Converse Router for Claude, Llama, and Mistral

import {
  BedrockRuntimeClient,
  ConverseCommand,
  ConverseStreamCommand,
  type ContentBlock,
  type InferenceConfiguration,
  type Message,
  type ToolConfiguration,
} from "@aws-sdk/client-bedrock-runtime";

export interface StandardizedConverseRequest {
  modelId: string; // e.g. Anthropic Claude, Meta Llama, or Mistral Bedrock model/profile ID
  systemPrompt?: string;
  messages: Message[];
  inferenceConfig?: InferenceConfiguration;
  toolConfig?: ToolConfiguration;
}

export interface StandardizedConverseResult {
  text: string;
  stopReason: string | undefined;
  inputTokens: number;
  outputTokens: number;
  rawAssistantMessage: Message | undefined;
}

export class BedrockConverseRouter {
  private readonly client: BedrockRuntimeClient;

  constructor(region = process.env.AWS_REGION ?? "us-east-1") {
    this.client = new BedrockRuntimeClient({ region });
  }

  async invoke(req: StandardizedConverseRequest): Promise<StandardizedConverseResult> {
    const command = new ConverseCommand({
      modelId: req.modelId,
      system: req.systemPrompt ? [{ text: req.systemPrompt }] : undefined,
      messages: req.messages,
      inferenceConfig: req.inferenceConfig ?? {
        maxTokens: 1024,
        temperature: 0.2,
        topP: 0.9,
      },
      toolConfig: req.toolConfig,
    });

    const response = await this.client.send(command);
    const assistantMsg = response.output?.message;
    const text = this.extractText(assistantMsg?.content);

    return {
      text,
      stopReason: response.stopReason,
      inputTokens: response.usage?.inputTokens ?? 0,
      outputTokens: response.usage?.outputTokens ?? 0,
      rawAssistantMessage: assistantMsg,
    };
  }

  async streamText(
    req: StandardizedConverseRequest,
    onTextDelta: (delta: string) => void
  ): Promise<{ stopReason?: string; inputTokens: number; outputTokens: number }> {
    const command = new ConverseStreamCommand({
      modelId: req.modelId,
      system: req.systemPrompt ? [{ text: req.systemPrompt }] : undefined,
      messages: req.messages,
      inferenceConfig: req.inferenceConfig ?? {
        maxTokens: 1024,
        temperature: 0.2,
        topP: 0.9,
      },
      toolConfig: req.toolConfig,
    });

    const response = await this.client.send(command);
    let stopReason: string | undefined;
    let inputTokens = 0;
    let outputTokens = 0;

    if (response.stream) {
      for await (const event of response.stream) {
        if (event.contentBlockDelta?.delta?.text) {
          onTextDelta(event.contentBlockDelta.delta.text);
        } else if (event.messageStop) {
          stopReason = event.messageStop.stopReason;
        } else if (event.metadata?.usage) {
          inputTokens = event.metadata.usage.inputTokens ?? inputTokens;
          outputTokens = event.metadata.usage.outputTokens ?? outputTokens;
        }
      }
    }

    return { stopReason, inputTokens, outputTokens };
  }

  private extractText(content: ContentBlock[] | undefined): string {
    if (!content) return "";
    return content
      .map((block) => ("text" in block && typeof block.text === "string" ? block.text : ""))
      .join("");
  }
}

// Example usage across Claude, Llama, and Mistral with one identical payload builder:
export function buildUserTurn(prompt: string): Message[] {
  return [{ role: "user", content: [{ text: prompt }] }];
}

Helpful Tips for Production Bedrock Converse Orchestration

  • Converse is stateless—always send full conversation history: Bedrock Converse does not persist chat sessions server-side; append each assistant response (output.message) and any toolResult messages to your messages array on every turn.
  • Keep prompts and tool schemas clean for open-weight models (Llama / Mistral): Even though Converse normalizes the wire format, Llama and Mistral models can be stricter about concise system instructions, valid JSON tool schemas, and alternating user/assistant roles than Claude—test each model in your fallback chain on real prompts.
  • Use inference profiles and BedrockRuntimeClient connection reuse: Reuse a single BedrockRuntimeClient instance across requests to preserve HTTP keep-alive connections, and configure inference profiles when cross-region routing or throughput controls are required.