AWS Builder Center

Building a Context-Aware AI Assistant in Electron with Amazon Bedrock

A technical guide to integrating Amazon Bedrock’s Converse API into an Electron application, grounding responses in safe UI context, and handling model availability across AWS Regions with runtime discovery and inference profiles.

Generative AI becomes much more useful when it understands what the user is currently doing. A generic assistant can answer a general question; a context-aware assistant can explain the active workspace, selected resource, current operation, or environment without forcing the user to repeat that information in every prompt.
That was our goal when integrating Amazon Bedrock into an Electron application. We wanted users to bring an existing AWS connection, discover model candidates in the selected account and Region, verify one with a real invocation, and receive answers grounded in the current application state. We also wanted the integration to behave predictably when the application’s primary AWS Region and the Bedrock runtime Region were different, or when a saved model identifier was not invokable after an account or Region change.
This article explains the architecture, the TypeScript implementation, the failure modes we encountered, and the model-resolution layer that made the integration Region-aware.
The examples are simplified from a production Electron implementation. Replace identifiers, limits, context fields, and IAM resources with values appropriate for your application.

What “context-aware” means in an Electron application

Our first design decision was to avoid treating “context” as “send everything in the renderer.”
For our assistant, context is a small allowlisted object containing non-sensitive application metadata such as:
  • active workspace and workflow;
  • AWS connection name and Region;
  • environment name and whether it is production;
  • selected service, resource type, and resource name;
  • current operation and view;
  • validation error and warning counts; and
  • other bounded facts already visible to the user.
We deliberately exclude credentials, secrets, personal data, raw records, arbitrary component state, and hidden browser or operating-system data.
This is prompt grounding, not necessarily a traditional retrieval-augmented generation (RAG) pipeline. The grounding data comes from the live application state, is bounded and sanitized locally, and is attached to each request.
The request path looks like this:
Electron renderer
|
v
Collect allowlisted UI context
|
v
Validated IPC request
|
v
Main-process context sanitization
|
v
Build grounded prompt + response contract
|
v
Resolve model for account and Bedrock runtime Region
|
v
Amazon Bedrock Converse API
|
v
Parse + validate structured response
|
v
Reviewable answer, evidence, and suggested actions

1. Keep AWS credentials in the main process

Electron separates the privileged main process from renderer processes, while a preload script can provide a narrowly scoped bridge. With context isolation enabled, the preload script runs in a separate JavaScript context from the loaded page. We keep AWS credentials and AWS SDK clients in the main process. The renderer can request an AI operation through the preload API, but it cannot read the credentials used to sign that request.
A minimal preload boundary can look like this:
// preload.ts
import { contextBridge, ipcRenderer } from "electron";

contextBridge.exposeInMainWorld("assistant", {
ask: (request: AssistantRequest) =>
ipcRenderer.invoke("ai:assist", request),
});
This pattern assumes  contextIsolation: true ,  nodeIntegration: false , and renderer sandboxing. Expose one narrowly scoped preload method per IPC operation instead of exposing raw  ipcRenderer . Electron’s  Context Isolation guide  explains why a context bridge alone is not enough if it exposes overly powerful methods.
The main process validates both the sender and the payload before it calls any provider:
// main/ipc.ts
import {
ipcMain,
type IpcMainInvokeEvent,
} from "electron";

function isTrustedSender(
event: IpcMainInvokeEvent
): boolean {
try {
const url = new URL(event.senderFrame.url);

// Replace this with the exact origin used by your app.
return (
url.protocol === "app:" &&
url.host === "desktop"
);
} catch {
return false;
}
}

ipcMain.handle("ai:assist", async (event, request) => {
if (!isTrustedSender(event)) {
throw new Error("Untrusted IPC sender.");
}

if (!request || typeof request.prompt !== "string") {
throw new Error("A valid prompt is required.");
}

if (
!request.context ||
typeof request.context.workspace !== "string"
) {
throw new Error("Valid workspace context is required.");
}

return aiService.assist(
request.prompt,
request.context
);
});
The exact sender check depends on whether the application loads a custom protocol, a local file, or trusted HTTPS content. Electron’s  security checklist  recommends validating the sender of every privileged IPC message.
Bedrock is represented as a first-class provider in our existing AI abstraction. Instead of asking for another provider API key, the user selects an AWS connection already configured in the application.
The saved AI configuration contains references, not credentials:
type AIProvider =
| "openai"
| "anthropic"
| "google"
| "bedrock"
| "custom";

interface AIConfig {
provider: AIProvider;
model: string;
awsConnectionId?: string;
bedrockRegion?: string;
enabled: boolean;
}
The main process resolves the connection and creates AWS SDK clients with the same credential provider used by the rest of the application. Local emulators and unrelated custom endpoints are rejected because they cannot represent a Bedrock control-plane or runtime connection.
This design gives us three useful properties:
  1. Bedrock follows the same account and session lifecycle as the rest of the application.
  1. Renderer code never receives AWS secrets.
  1. Every provider request crosses an explicit, testable IPC boundary.

2. Build a strict context boundary

Context-aware output is only trustworthy when the context boundary is explicit. We use an allowlist instead of recursively serializing React state, Redux stores, component props, or the DOM:
const ALLOWED_CONTEXT_FIELDS = [
"workspace",
"workflow",
"surface",
"connectionName",
"region",
"environmentName",
"production",
"serviceName",
"resourceType",
"resourceName",
"resourceStatus",
"operation",
"selectedObjectName",
"resultCount",
"validationErrorCount",
"validationWarningCount",
] as const;

function sanitizeWorkspaceContext(
input: Record<string, unknown>
): Record<string, string | number | boolean> {
const output: Record<string, string | number | boolean> = {};

for (const field of ALLOWED_CONTEXT_FIELDS) {
const value = input[field];

if (typeof value === "string" && value.trim()) {
output[field] = value.trim().slice(0, 240);
} else if (
typeof value === "number" &&
Number.isFinite(value)
) {
output[field] = value;
} else if (typeof value === "boolean") {
output[field] = value;
}
}

return output;
}
Strings are trimmed and bounded, numbers must be finite, and unknown fields are dropped. This is intentionally boring code. The less surprising the context serializer is, the easier it is to review and test.
We then place the sanitized metadata inside a prompt with a constrained response schema:
const safeContext = sanitizeWorkspaceContext(context);

const prompt = `You are a contextual assistant inside an Electron application.
Answer using only the supplied non-sensitive workspace context and established
AWS practices. State uncertainty and missing evidence explicitly.

WORKSPACE CONTEXT:
${JSON.stringify(safeContext, null, 2)}

USER QUESTION:
${userPrompt}

Return ONLY valid JSON:
{
"answer": "Grounded answer",
"evidence": [
{ "label": "Context field", "value": "Observed value" }
],
"suggestedActions": [
{
"title": "Next action",
"reason": "Why it helps",
"risk": "low|medium|high"
}
]
}`;
The model is instructed that evidence must be directly derived from the supplied context. We still validate the returned JSON, cap array lengths and string lengths, and treat every suggested action as a proposal. Generated text never becomes authorization to mutate local state or AWS resources.
For multi-turn chat, prior messages and optional user-authored notes are marked as untrusted quoted data. We redact credential-shaped values and block explicit instruction-override or secret-exfiltration patterns before sending a request. These checks are defense in depth, not a replacement for authorization.

3. Use the Converse API as the provider boundary

Amazon Bedrock’s Converse API provides one message interface across supported models. That allowed our higher-level assistant code to remain provider-neutral while Bedrock-specific code handled credentials, Region selection, model resolution, timeouts, and AWS errors. AWS documents the request fields and required  bedrock:InvokeModel  permission in the  Converse API guide .
A simplified invocation looks like this:
import {
BedrockRuntimeClient,
ConverseCommand,
} from "@aws-sdk/client-bedrock-runtime";
import type {
AwsCredentialIdentity,
AwsCredentialIdentityProvider,
} from "@smithy/types";

interface InvokeInput {
region: string;
credentials:
| AwsCredentialIdentity
| AwsCredentialIdentityProvider;
modelId: string;
prompt: string;
maxTokens: number;
signal: AbortSignal;
}

async function invokeBedrock({
region,
credentials,
modelId,
prompt,
maxTokens,
signal,
}: InvokeInput): Promise<string> {
const client = new BedrockRuntimeClient({
region,
credentials,
maxAttempts: 5,
});

const response = await client.send(
new ConverseCommand({
modelId,
messages: [
{
role: "user",
content: [{ text: prompt }],
},
],
inferenceConfig: {
maxTokens,
temperature: 0.1,
},
}),
{ abortSignal: signal }
);

return (
response.output?.message?.content
?.map((block) =>
"text" in block ? block.text ?? "" : ""
)
.join("") ?? ""
);
}
For the chat models enabled in our application, we chose a low temperature because the assistant produces operational guidance and structured JSON, not creative prose. Confirm that each inference parameter is supported by the selected model. At the boundary we also enforce a prompt byte limit, a maximum output budget, a two-minute timeout, user cancellation, and friendly mappings for access denial, throttling, unavailable models, and temporarily unavailable models.
The  modelId  field can contain either a foundation model identifier or an inference profile identifier or ARN. That detail is central to the multi-Region solution; AWS describes the accepted resource types in its  inference API documentation .

4. The Region and model problem

A static model dropdown worked in a prototype and failed in a real application.
Consider an Electron application that:
  • uses one AWS Region for its primary workload;
  • is allowed to invoke Bedrock from a different Region;
  • saved a base model ID in one environment;
  • later switches AWS account or Region;
  • uses a model that requires a geographic inference profile; or
  • has an application inference profile for cost attribution.
A model name is therefore not enough. Availability depends on the account, source Region, inference type, lifecycle status, and permissions.
Cross-Region profiles add a second distinction: the application sends the request to a source Region, while Bedrock may route it to one of the profile’s destination Regions. AWS explains that relationship in  Supported Regions and models for inference profiles .
Our solution has three parts.

4.1 Decouple the Bedrock runtime Region from the application Region

The selected AWS connection still supplies credentials and a default Region, but users can choose a separate Bedrock runtime Region. We overlay that Region for the request instead of mutating the saved connection:
const storedConnection =
await connectionStore.getById(connectionId);

if (!storedConnection) {
throw new Error("The selected AWS connection no longer exists.");
}

const runtimeConnection = bedrockRegion
? { ...storedConnection, region: bedrockRegion }
: storedConnection;
The same effective Region is used for:
  • model discovery;
  • inference-profile discovery;
  • model resolution;
  • connection testing; and
  • the  BedrockRuntimeClient .
This prevents a subtle class of bugs in which the settings UI discovers models in one Region and the main process invokes from another.

4.2 Discover Region-available candidates

We query both the foundation-model catalog and inference profiles for the selected account and source Region. This creates a catalog of relevant candidates exposed by the Bedrock control plane; it does not by itself prove that the caller has invocation permission, that every provider-specific access prerequisite is complete, or that capacity is currently available:
import {
BedrockClient,
ListFoundationModelsCommand,
ListInferenceProfilesCommand,
} from "@aws-sdk/client-bedrock";

async function discoverModels(connection: AwsConnection) {
const client = new BedrockClient({
region: connection.region,
credentials: connection.credentials,
maxAttempts: 4,
});

const [foundationPage, profilePages] =
await Promise.all([
client.send(
new ListFoundationModelsCommand({
byOutputModality: "TEXT",
})
),
listAllInferenceProfiles(client),
]);

const directModels =
(foundationPage.modelSummaries ?? []).filter(
(model) =>
model.modelId &&
model.modelLifecycle?.status !== "LEGACY" &&
model.outputModalities?.includes("TEXT") &&
model.inferenceTypesSupported?.includes("ON_DEMAND")
);

const profiles = profilePages
.flatMap(
(page) => page.inferenceProfileSummaries ?? []
)
.filter(
(profile) =>
profile.status === "ACTIVE" &&
profile.inferenceProfileId
);

return normalizeAndDeduplicate(
directModels,
profiles
);
}
 ListInferenceProfiles  is paginated, so our implementation follows  nextToken :
async function listAllInferenceProfiles(
client: BedrockClient
) {
const pages = [];
let nextToken: string | undefined;

do {
const page = await client.send(
new ListInferenceProfilesCommand({
maxResults: 1000,
nextToken,
})
);

pages.push(page);
nextToken = page.nextToken;
} while (nextToken);

return pages;
}
We intentionally do not filter by profile type. That returns both AWS system-defined profiles and account-owned application profiles. The  ListInferenceProfiles API  exposes the profile type, status, IDs or ARNs, and referenced model ARNs.
We normalize every option into one shape:
interface BedrockModelOption {
id: string; // value accepted by Converse
name: string;
foundationModelId: string;
source:
| "foundation-model"
| "inference-profile";
routing:
| "in-region"
| "geographic"
| "global"
| "application";
aliases?: string[];
destinationRegions?: string[];
}
For application inference profiles, the invocation value is the profile ARN. For system-defined cross-Region profiles, it is typically the inference profile ID. The referenced foundation-model ARN gives us the canonical model identity and the destination Regions.
Discovery results are cached for a short period using a key derived from connection ID, Region, and credential identity. A Region or identity switch cannot reuse another account’s catalog.
Before saving a Bedrock configuration, we send a small  Converse  request through the same resolver, credentials, source Region, and runtime path used by normal requests. A successful response confirms, at test time, that those credentials can resolve and invoke the selected candidate through the configured source Region using  Converse . It does not guarantee future capacity or prove that every possible destination of a cross-Region profile is permitted.

4.3 Repair stale identifiers without changing model families

The hardest question was what to do when a previously saved identifier was unavailable in the new Region.
Silently choosing any available model would be dangerous. A different family can change cost, latency, context limits, output behavior, and governance assumptions. Instead, we repair the configuration only when we can prove that the replacement points to the same foundation model.
function resolveModel(
configured: string,
catalog: BedrockModelCatalog
): BedrockModelOption {
const exact = catalog.models.find(
(option) =>
option.id === configured ||
option.aliases?.includes(configured)
);

if (exact) return exact;

const canonicalId =
canonicalFoundationModelId(
configured,
catalog
);

const replacement = catalog.models
.filter(
(option) =>
option.foundationModelId === canonicalId &&
option.routing !== "application"
)
.sort(byRoutingPreference)[0];

if (replacement) return replacement;

throw new Error(
`Model "${configured}" is unavailable in ` +
`${catalog.region}. Choose a verified model.`
);
}
The automatic-repair preference is:
  1. direct in-Region on-demand model;
  1. geography-bound inference profile; and
  1. global inference profile.
Application profiles are not an automatic fallback. They can carry cost-allocation and ownership meaning, so we accept one only when the configured ID or alias explicitly identifies it. In that case, we resolve the alias to the account ARN. Otherwise, automatic repair excludes application profiles.
Inference profiles are designed for this invocation model. AWS documents that they can be supplied to  Converse , and that cross-Region profiles can improve throughput by routing within their configured destinations in  Set up a model invocation resource using inference profiles .

5. Make failures actionable

Regional failures often look similar but require different fixes. We translate AWS errors at the provider boundary:
  •  AccessDeniedException : verify the selected connection and permissions.
  •  UnrecognizedClientException : AWS rejected the credentials or session; verify the connection, source Region, and any Region-scoped session.
  •  ExpiredTokenException : reconnect or refresh the AWS session.
  •  ResourceNotFoundException : the selected model or profile could not be found in the effective Region.
  •  ValidationException : the identifier or inference request is invalid; report the sanitized model and Region context instead of assuming a single cause.
  •  ThrottlingException  or  ServiceQuotaExceededException : retry later or review quotas.
  •  ModelNotReadyException  or  ModelTimeoutException : retry the same verified model shortly.
  • networking errors: check connectivity and the selected Region.
Model discovery needs permission to list foundation models and inference profiles. Invocation needs  bedrock:InvokeModel ; using an inference profile also requires  bedrock:GetInferenceProfile . AWS summarizes these permissions in  Prerequisites for running model inference .
For cross-Region inference, IAM policies and Service Control Policies must allow the required actions for every destination Region in the chosen profile. Blocking one destination can fail the request even when other destinations are allowed. This is an important deployment check, not something an application should try to bypass.

6. Add timeouts, cancellation, and size limits

Desktop applications need to remain responsive even when a provider is slow. We link an external cancellation signal to a provider timeout:
function createRequestController(
timeoutMs: number,
externalSignal?: AbortSignal
) {
const controller = new AbortController();

const abortFromExternal = () =>
controller.abort(externalSignal?.reason);

if (externalSignal?.aborted) {
abortFromExternal();
} else {
externalSignal?.addEventListener(
"abort",
abortFromExternal,
{ once: true }
);
}

const timer = setTimeout(
() => controller.abort(),
timeoutMs
);

return {
signal: controller.signal,
cleanup: () => {
clearTimeout(timer);
externalSignal?.removeEventListener(
"abort",
abortFromExternal
);
},
};
}
We validate the model identifier, prompt byte size, and output-token range before creating the runtime client. A request that cannot be valid should fail locally with a useful message.
Cancellation and timeout are also reported differently. “The user cancelled this turn” is not the same operational event as “the provider did not respond within two minutes.”

7. Audit metadata, not conversations

Operational visibility is useful, but prompt logging can defeat the privacy boundary we just created. Our audit record stores:
  • provider and operation;
  • success or failure;
  • connection reference, source Region, and resolved model;
  • request and response byte counts;
  • input and output token counts when returned;
  • latency and stop reason; and
  • a bounded error code.
It never stores prompt text, response text, credentials, or raw provider errors. In our implementation, audit events are hash-linked, which detects a broken chain or edits that do not recompute subsequent hashes. Because the chain is not externally signed or anchored, it is not proof against an actor who can rewrite the entire audit store. Higher-assurance deployments should sign records or export them to an independently controlled log.
We also treat guardrail intervention and content filtering as explicit failures, reject empty model output, and distinguish user cancellation from timeout.

8. Validate model output before rendering actions

A JSON response is not automatically a valid application response. We parse the first complete JSON object, validate its required fields, bound every string and array, and discard unknown action shapes.
The UI renders suggestions as reviewable cards. If a workflow can perform an operation, the application independently checks:
  • whether the tool is registered;
  • whether its input matches a fixed schema;
  • whether the active user and environment allow it;
  • whether confirmation or approval is required; and
  • whether the operation is read-only or mutating.
The model can propose an action. It cannot grant itself a tool, invent an approval, or claim that an operation succeeded without a trusted result from the application.

9. Test the resolver as a pure subsystem

The model resolver is mostly pure logic with injectable discovery dependencies. That makes the difficult cases easy to test without calling AWS.
Our tests cover:
it("uses an explicit Bedrock Region without mutating the base connection");
it("returns only active text models and profiles");
it("prefers in-region, then geographic, then global routing");
it("maps a saved base model to the same-model geographic profile");
it("preserves verified direct and profile identifiers");
it("requires explicit selection for application profiles");
it("moves a saved profile across geographies by foundation identity");
it("rejects an unrelated model instead of guessing another family");
it("maps IAM, expired-session, Region, and network failures");
it("records invocation metadata without prompt or response content");
One especially valuable test uses fictional Region and provider names. That proves the resolver depends on ARN structure and discovered metadata, not a growing list of hardcoded model prefixes.
We also test the Electron boundary: the renderer receives the expected API, only allowlisted IPC channels are exposed, invalid context is rejected, and local or custom endpoints cannot be used as Bedrock connections.

What we learned

The Bedrock API call was the smallest part of this feature. The production work was defining the contracts around it.
First, context awareness should be an explicit data boundary. An allowlist produces better prompts and a better security story than dumping renderer state into a model.
Second, Electron’s process boundary is useful only when it is enforced. Keep credentials and provider clients in the main process, expose narrow preload methods, and validate both the sender and payload of every privileged IPC request.
Third, Region is part of model identity. Store the user’s intent, but verify invokability against the active account and source Region before saving or invoking a model.
Fourth, inference profiles are not merely a throughput toggle. They affect routing, IAM, SCPs, data-residency decisions, observability, and cost attribution. Surface those choices in the UI.
Fifth, automatic repair should preserve semantics. Switching from a base ID to a verified profile for the same foundation model is reasonable; switching to a different model family is a user decision.
Finally, make the output reviewable. Structured responses, evidence derived from trusted metadata, explicit uncertainty, and human-gated actions are what turn an LLM response into an application feature.

Closing

By combining Electron process isolation, a strict context boundary, Amazon Bedrock’s Converse API, per-Region discovery, and inference-profile-aware model resolution, we built an assistant that understands the active application workflow without pretending that every model is available everywhere.
The architecture is reusable for Electron applications that span AWS accounts, Regions, or model families:
  1. collect only the UI context the assistant needs;
  1. sanitize it before it leaves the device;
  1. keep credentials and SDK clients in the main process;
  1. discover Region-available candidates and verify the selected configuration with a real invocation;
  1. resolve identifiers by canonical model identity;
  1. invoke through a narrow provider boundary;
  1. validate structured output; and
  1. keep execution and authorization outside the model.
That separation is what made the context-aware Bedrock integration reliable enough to become an application capability rather than remain a prototype.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article