DEV Community

Dinesh_gowtham
Dinesh_gowtham

Posted on

How to Build a Multi‑Agent Collaboration Workflow with Bedrock Agents and OpenSearch, Explained Simply

You’ve seen single‑LLM assistants, but real‑world coding helpers need teams of specialized agents that talk to each other. Bedrock’s new multi‑agent orchestration lets you stitch together a code‑writer, a reviewer, and a knowledge‑base searcher—all in one flow. In this guide you’ll see how to wire those agents together with a Lambda orchestrator and an OpenSearch knowledge base.


Why Multi‑Agent Collaboration Matters

The problem with “one big brain”

A single language model (LLM) can generate code, answer questions, and even debug. But each of those tasks stresses the model in a different way. When you ask it to write a function and enforce style guidelines, you are asking it to juggle two jobs at once. The result is often a compromise: the code works but the style is off, or the style is perfect but the logic has bugs.

How dividing labor helps

Think of a software team: a writer drafts the implementation, a reviewer checks for bugs and style, and a searcher pulls in existing snippets from a knowledge base. Each person focuses on what they do best, and the final product is higher quality. The same idea applies to LLMs when you treat each model (or each “agent” — a model paired with a purpose‑specific prompt) as a specialist.

In plain English: Splitting a tough job into smaller, focused jobs usually gives a better answer, just like a real development team.

Why Bedrock now supports orchestration

Amazon Bedrock introduced agents (a model plus a system prompt) and an orchestration API that lets you chain them together. The orchestration layer tracks the conversation, passes tool results, and decides which agent runs next. This means you can build a workflow that looks like:

  1. Code‑writer → 2. Reviewer → 3. Searcher → 4. Combine & return

The rest of this post shows how to materialize that flow inside an AWS Lambda function and connect it to an OpenSearch index that stores reusable code snippets.


Bedrock Agent Orchestration Basics

What is a Bedrock “agent”?

An agent in Bedrock is a language model (e.g., anthropic.claude-v2) paired with a system prompt that tells the model what its role is. The system prompt is a short piece of text that the model sees before any user message; it shapes the model’s behavior.

Term Meaning
Model The underlying LLM that does the heavy lifting.
System prompt A fixed instruction that defines the agent’s persona.
Tool A function the agent can call (e.g., “search OpenSearch”).
Orchestration The process that decides which agent runs next and routes tool results.

Minimal Bedrock call with the JavaScript SDK

Below is the smallest possible request that invokes a model directly. In a real orchestrated flow you would not call invokeModel yourself; the orchestrator does it for you. However, understanding the raw call helps you see what the orchestrator wraps.

// file: bedrockRawInvoke.ts
import {
  BedrockRuntimeClient,
  InvokeModelCommand,
} from "@aws-sdk/client-bedrock-runtime";

// Create a client that talks to the Bedrock service in the current region
const client = new BedrockRuntimeClient({ region: "us-east-1" });

async function invokeClaude(prompt: string) {
  // The body must be JSON, then encoded as a Uint8Array
  const input = {
    body: JSON.stringify({ prompt, max_tokens: 1024 }),
    modelId: "anthropic.claude-v2", // Choose a model that supports tool use
    contentType: "application/json",
    accept: "application/json",
  };

  // The SDK command sends the request and returns a streaming response object
  const command = new InvokeModelCommand(input);
  const response = await client.send(command);

  // The response body is a Uint8Array – decode it to a string
  const raw = new TextDecoder("utf-8").decode(response.body);
  const parsed = JSON.parse(raw);
  console.log("Model output:", parsed.completion);
}

invokeClaude("Write a one‑line hello world in JavaScript.");
Enter fullscreen mode Exit fullscreen mode

Expected output (the exact wording depends on the model, but you’ll see a short code snippet):

Model output: console.log("Hello, world!");
Enter fullscreen mode Exit fullscreen mode

Known Bedrock gotchas you’ll hit early

Gotcha What it looks like How to avoid it
Token limits per minute After a few rapid calls you get ThrottlingException. Implement exponential back‑off and keep track of requests per minute.
Streaming responses need manual SSE parsing The SDK returns a raw stream; response.body is not a finished string. Use a helper that reads the stream line‑by‑line, or set accept: "application/json" for non‑streaming.
Knowledge‑base sync delay Newly uploaded documents are not searchable for up to 5 minutes. Insert a short wait or poll the index before relying on immediate results.
Model selection matters Some models cannot call tools (e.g., ai21.j2-mid). Pick a model that lists tool_use in its capabilities, like Claude‑v2.
Cross‑region latency When you call a model in us-west-2 from a Lambda in eu-central-1 the response can be > 2 seconds. Keep Lambda and Bedrock in the same region for low latency.

Tip: Keep a small “metrics” object in your Lambda that records how many Bedrock calls you make per minute; you can log it to CloudWatch and set an alarm before you hit the limit.


Setting Up OpenSearch as a Knowledge Base

What is OpenSearch?

OpenSearch is an open‑source search engine that Amazon runs as a managed service. It stores documents (JSON blobs) in an index and lets you query them with a DSL that looks like JSON. For our workflow we’ll store reusable code snippets so the reviewer can fetch examples that match the current context.

Create a domain and index (high‑level steps)

  1. Open the OpenSearch console → Create domain → choose “development” tier.
  2. In the Access policy tab, add a statement that allows the Bedrock service principal (bedrock.amazonaws.com) and your Lambda execution role to es:ESHttpPost and es:ESHttpGet.
  3. After the domain is active, use the Dev Tools console to create an index:
PUT /code-snippets
{
  "settings": {
    "number_of_shards": 1,
    "number_of_replicas": 0
  },
  "mappings": {
    "properties": {
      "language": { "type": "keyword" },
      "tags":     { "type": "keyword" },
      "code":     { "type": "text" },
      "description": { "type": "text" }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode
  1. Populate the index with a few sample snippets:
POST /code-snippets/_doc
{
  "language": "javascript",
  "tags": ["array", "map"],
  "code": "const squares = arr.map(x => x * x);",
  "description": "Map over an array to compute squares."
}
Enter fullscreen mode Exit fullscreen mode

OpenSearch SDK gotchas

Gotcha Symptom Fix
Domain policy missing Bedrock principal The search step returns AccessDeniedException and looks like “no results”. Explicitly add "Service": "bedrock.amazonaws.com" to the policy’s Principal.
VPC‑only domain Lambda outside the VPC cannot reach the endpoint, leading to timeout. Deploy Lambda in the same VPC/subnet or switch the domain to “public access”.
Signed request required Using the client without credentials yields a 403 error. Ensure the Lambda role has es:ESHttp* permissions and the SDK picks up default credentials.
Index refresh delay After indexing a new document, a search may miss it for a second. Call POST /_refresh or wait a short period before the next query.

In plain English: If your search always returns “nothing”, the first thing to check is the OpenSearch access policy – it must explicitly allow Bedrock and your Lambda to call it.


Lambda Orchestrator Code Walkthrough

High‑level flow

  1. Receive a developer request (e.g., “Write a function that debounces a button click”).
  2. Invoke the code‑writer agent → get draft code.
  3. Pass the draft to the reviewer agent → get reviewed code plus a list of suggested tags.
  4. Search OpenSearch with those tags → pull matching snippets.
  5. Combine everything into a friendly JSON response.

The Lambda runs on Node.js 22 and uses the fetch API for Bedrock (because the SDK’s invokeModel is a thin wrapper around HTTP) and the @aws-sdk/client-opensearch for searching.

Complete, runnable TypeScript example

Prerequisites

  • Node 22 runtime (available in Lambda).
  • IAM role with bedrock:InvokeModel and es:ESHttp* permissions.
  • Environment variables: BEDROCK_MODEL_WRITER, BEDROCK_MODEL_REVIEWER, OPENSEARCH_ENDPOINT, OPENSEARCH_INDEX.
// file: handler.ts
import {
  BedrockRuntimeClient,
  InvokeModelCommand,
} from "@aws-sdk/client-bedrock-runtime";
import {
  OpenSearchClient,
  SearchCommand,
} from "@aws-sdk/client-opensearch";
import { APIGatewayProxyEvent, APIGatewayProxyResult } from "aws-lambda";

// ---------- Configuration ----------
const REGION = process.env.AWS_REGION || "us-east-1";
const writerModel = process.env.BEDROCK_MODEL_WRITER || "anthropic.claude-v2";
const reviewerModel = process.env.BEDROCK_MODEL_REVIEWER || "anthropic.claude-v2";
const opensearchEndpoint = process.env.OPENSEARCH_ENDPOINT!;
const opensearchIndex = process.env.OPENSEARCH_INDEX!;

// ---------- Clients ----------
const bedrock = new BedrockRuntimeClient({ region: REGION });
const opensearch = new OpenSearchClient({
  region: REGION,
  endpoint: opensearchEndpoint, // e.g. https://search-my-domain.region.es.amazonaws.com
});

// ---------- Helper: invoke a Bedrock agent ----------
async function invokeAgent(
  modelId: string,
  systemPrompt: string,
  userMessage: string,
  tools?: any[]
) {
  // Build the tool‑aware message format expected by Claude‑v2
  const messages = [
    { role: "system", content: systemPrompt },
    { role: "user", content: userMessage },
  ];
  if (tools) {
    // Attach tool definitions so the model can call them
    (messages as any).push({ role: "assistant", tool_definitions: tools });
  }

  const payload = {
    body: JSON.stringify({ messages, max_tokens: 2048, temperature: 0.2 }),
    modelId,
    contentType: "application/json",
    accept: "application/json",
  };
  const command = new InvokeModelCommand(payload);
  const response = await bedrock.send(command);
  const raw = new TextDecoder("utf-8").decode(response.body);
  const parsed = JSON.parse(raw);
  // The model returns an array of messages; we only need the last content
  const assistantMessage = parsed.messages?.pop()?.content;
  return assistantMessage ?? "";
}

// ---------- Helper: search OpenSearch ----------
async function searchSnippets(tags: string[]) {
  const query = {
    index: opensearchIndex,
    body: {
      size: 3,
      query: {
        terms: { tags },
      },
    },
  };
  const command = new SearchCommand(query);
  const resp = await opensearch.send(command);
  // Map the hits to a simple array of code snippets
  return resp.hits?.hits?.map((h) => ({
    id: h._id,
    code: (h._source as any).code,
    description: (h._source as any).description,
  })) ?? [];
}

// ---------- Lambda entry point ----------
export const handler = async (
  event: APIGatewayProxyEvent
): Promise<APIGatewayProxyResult> => {
  try {
    const body = JSON.parse(event.body ?? "{}");
    const developerRequest = body.request ?? "Write a JavaScript debounce function";

    // 1️⃣ Code‑writer agent
    const writerPrompt = `You are a helpful code writer. Generate clean, commented JavaScript that fulfills the user request.`;
    const draft = await invokeAgent(writerModel, writerPrompt, developerRequest);

    // 2️⃣ Reviewer agent – ask it to point out missing tags
    const reviewerPrompt = `You are a senior reviewer. Read the supplied code and list up to three tags that describe its purpose (e.g., "debounce", "event", "throttle"). Return ONLY a JSON array of tags.`;
    const tagsJson = await invokeAgent(reviewerModel, reviewerPrompt, draft);
    let tags: string[];
    try {
      tags = JSON.parse(tagsJson);
    } catch {
      tags = []; // fallback if model didn't output JSON
    }

    // 3️⃣ Search OpenSearch for matching snippets
    const snippets = await searchSnippets(tags);

    // 4️⃣ Assemble final response
    const result = {
      draft,
      tags,
      relatedSnippets: snippets,
    };

    return {
      statusCode: 200,
      body: JSON.stringify(result, null, 2),
      headers: { "Content-Type": "application/json" },
    };
  } catch (err) {
    console.error("Orchestration error:", err);
    return {
      statusCode: 500,
      body: JSON.stringify({ error: "Internal server error" }),
    };
  }
};
Enter fullscreen mode Exit fullscreen mode

What you’ll see when you invoke the Lambda (via API Gateway or aws lambda invoke):

{
  "draft": "function debounce(func, wait) {\n  let timeout;\n  return function executedFunction(...args) {\n    const later = () => {\n      clearTimeout(timeout);\n      func.apply(this, args);\n    };\n    clearTimeout(timeout);\n    timeout = setTimeout(later, wait);\n  };\n}",
  "tags": ["debounce", "event", "throttle"],
  "relatedSnippets": [
    {
      "id": "abc123",
      "code": "const throttle = (fn, limit) => { let inThrottle; return function() { const args = arguments; if (!inThrottle) { fn.apply(this, args); inThrottle = true; setTimeout(() => (inThrottle = false), limit); } }; };",
      "description": "Simple throttle implementation."
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

The response shows the draft code, the tags the reviewer suggested, and a couple of related snippets pulled from OpenSearch. You can now surface this JSON in a UI, copy the code, or let the user request refinements.

Key takeaway: By separating generation, review, and lookup into distinct agents, the Lambda stays tiny and each step can be swapped out independently (e.g., replace the reviewer with a different LLM).

Analogy: a kitchen assembly line

Imagine a sandwich shop: one worker spreads the bread, another adds fillings, a third adds the sauce, and a fourth checks the order before handing it to the customer. The shop runs faster and makes fewer mistakes than a single person trying to do everything. Our Lambda orchestrator is the “order‑taker” that tells each worker (agent) when to act and then packages the final sandwich (response) for the developer.


Handling Errors and Gotchas

Silent AccessDeniedException from OpenSearch

If you forget to add the Bedrock service principal to the OpenSearch domain policy, the search call fails with AccessDeniedException. The Lambda logs will show the exception, but the JSON response will simply have an empty relatedSnippets array, making it look like the search found nothing.

How to catch it early

// inside searchSnippets()
try {
  const resp = await opensearch.send(command);
  return resp.hits?.hits?.map(...);
} catch (e: any) {
  if (e.name === "AccessDeniedException") {
    console.error("🔒 OpenSearch policy missing Bedrock principal!");
  }
  throw e; // re‑throw so the outer handler returns 500
}
Enter fullscreen mode Exit fullscreen mode

Tip: Add a CloudWatch metric filter for the string “AccessDeniedException” and set an alarm; you’ll know instantly when the policy drifts.

Rate‑limit handling for Bedrock

Bedrock enforces a tokens‑per‑minute quota, not a request‑per‑minute limit. If you send many large prompts in a short burst you may exceed the token budget and receive ThrottlingException.

Simple back‑off strategy

async function invokeWithBackoff(...args: Parameters<typeof invokeAgent>) {
  let attempts = 0;
  while (true) {
    try {
      return await invokeAgent(...args);
    } catch (e: any) {
      if (e.name === "ThrottlingException" && attempts < 5) {
        const delay = Math.pow(2, attempts) * 200; // 200ms, 400ms, 800ms…
        await new Promise((res) => setTimeout(res, delay));
        attempts++;
      } else {
        throw e;
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Replace calls to invokeAgent with invokeWithBackoff to smooth spikes.

Streaming vs. non‑streaming

When you ask Bedrock for a streaming response (accept: "text/event-stream"), the SDK gives you a raw byte stream that you must parse line by line. For most orchestration tasks you want the full JSON payload at once, so set accept: "application/json" as shown in the code. If you ever need streaming (e.g., real‑time UI updates), wrap the stream in an async iterator that yields each data: line.

In plain English: Use the JSON response unless you have a very specific reason to stream; it saves you a lot of parsing work.


The Takeaway

Key points to remember

  • Splitting a complex coding task into writer → reviewer → searcher mirrors how human teams work and improves output quality.
  • A Bedrock agent is just a model plus a system prompt; the orchestration layer lets you chain agents without writing custom glue code.
  • OpenSearch acts as a searchable knowledge base; its access policy must explicitly allow both Bedrock and your Lambda.
  • Rate limits on Bedrock are token‑based; implement exponential back‑off to stay under the quota.
  • Streaming responses require extra parsing; stick with JSON (accept: "application/json") for orchestration pipelines.
  • The full Lambda example shows a minimal, runnable workflow that you can copy, tweak, and expand.

Conclusion

Building a multi‑agent AI assistant may sound intimidating, but when you break it into three clear responsibilities—generation, review, and knowledge retrieval—the pieces fit together nicely. The Bedrock runtime gives you a simple HTTP‑style call to any model, while the OpenSearch client lets you pull context from an existing code library. By wiring these calls inside a lightweight Lambda orchestrator you get a scalable, serverless workflow that can evolve: swap the writer model, add more reviewers, or enrich the knowledge base with additional indices.

Give the pattern a try in a sandbox account, watch the logs for the two common gotchas (policy‑denied OpenSearch and Bedrock throttling), and you’ll have a solid foundation for building AI‑powered developer tools that feel like a real team rather than a single, over‑worked chatbot. Happy coding!


Transparency notice

This article was written with the help of an AI system — Groq (GPT OSS 120B).

Published: 2026-11-30 · Primary focus: Bedrock

All code blocks are intended to be correct and runnable, but please verify them
against the official docs for the tools mentioned before using in production.

Find an error? Drop a comment — corrections are always welcome.

Top comments (0)