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
messageswithrole("user"or"assistant") and an array of typedContentBlockobjects ({ text },{ image },{ document },{ toolUse },{ toolResult }), while system instructions live in the top-levelsystemparameter ([{ text: "..." }]) rather than provider-specific fields. - Normalized inference parameters and response envelope: Common controls such as
maxTokens,temperature,topP, andstopSequencessit insideinferenceConfig, and responses return a consistentoutput.message,stopReason("end_turn","tool_use","max_tokens"),usage, andmetricsshape regardless of whether you target Claude, Llama, or Mistral. - Model-specific escape hatch (
additionalModelRequestFields): When a parameter is unique to one model family (such astop_kor reasoning/thinking options), you can pass provider-specific fields viaadditionalModelRequestFieldswithout breaking the commonmessagesandinferenceConfigcontract.
Steps to Standardize Multi-Model Calls with Bedrock Converse
- Swap
modelId(or inference profile) without rewriting payloads: Keep one canonicalMessage[],system,inferenceConfig, andtoolConfigbuilder in your orchestration layer and route dynamically across Anthropic Claude, Meta Llama, and Mistral model IDs or cross-region inference profiles. - Use
toolConfigwithtoolSpec.inputSchema.jsonfor function calling: Define tools once intoolConfig, append the assistant’soutput.messagecontainingtoolUseblocks back tomessages, execute the tool, and return ausermessage containing{ toolResult: { toolUseId, content } }. - Use
ConverseStreamCommandfor real-time streaming: StreamcontentBlockDeltaevents for text or tool input JSON and readmessageStop/metadataforstopReasonand token counts using the same request structure. - Guard against per-model feature differences: Verify model-level support in your target AWS Region for features like tool calling, vision/document blocks, or
systemprompts 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
assistantresponse (output.message) and anytoolResultmessages to yourmessagesarray 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/assistantroles than Claude—test each model in your fallback chain on real prompts. - Use inference profiles and
BedrockRuntimeClientconnection reuse: Reuse a singleBedrockRuntimeClientinstance across requests to preserve HTTP keep-alive connections, and configure inference profiles when cross-region routing or throughput controls are required.
You must log in or register to comment.
