Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8.x] [Security solution] Use `BedrockRuntimeClient` to interact with converse APIs (#201046) #201289

Merged
merged 1 commit into from
Nov 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,17 @@
import {
BedrockRuntimeClient as _BedrockRuntimeClient,
BedrockRuntimeClientConfig,
ConverseCommand,
ConverseResponse,
ConverseStreamCommand,
ConverseStreamResponse,
} from '@aws-sdk/client-bedrock-runtime';
import { constructStack } from '@smithy/middleware-stack';
import { HttpHandlerOptions } from '@smithy/types';
import { PublicMethodsOf } from '@kbn/utility-types';
import type { ActionsClient } from '@kbn/actions-plugin/server';

import { NodeHttpHandler } from './node_http_handler';
import { prepareMessages } from '../../utils/bedrock';

export interface CustomChatModelInput extends BedrockRuntimeClientConfig {
actionsClient: PublicMethodsOf<ActionsClient>;
Expand All @@ -23,15 +28,51 @@ export interface CustomChatModelInput extends BedrockRuntimeClientConfig {

export class BedrockRuntimeClient extends _BedrockRuntimeClient {
middlewareStack: _BedrockRuntimeClient['middlewareStack'];
streaming: boolean;
actionsClient: PublicMethodsOf<ActionsClient>;
connectorId: string;

constructor({ actionsClient, connectorId, ...fields }: CustomChatModelInput) {
super(fields ?? {});
this.config.requestHandler = new NodeHttpHandler({
streaming: fields.streaming ?? true,
actionsClient,
connectorId,
});
this.streaming = fields.streaming ?? true;
this.actionsClient = actionsClient;
this.connectorId = connectorId;
// eliminate middleware steps that handle auth as Kibana connector handles auth
this.middlewareStack = constructStack() as _BedrockRuntimeClient['middlewareStack'];
}

public async send(
command: ConverseCommand | ConverseStreamCommand,
optionsOrCb?: HttpHandlerOptions | ((err: unknown, data: unknown) => void)
) {
const options = typeof optionsOrCb !== 'function' ? optionsOrCb : {};
if (command.input.messages) {
// without this, our human + human messages do not work and result in error:
// A conversation must alternate between user and assistant roles.
command.input.messages = prepareMessages(command.input.messages);
}
const data = (await this.actionsClient.execute({
actionId: this.connectorId,
params: {
subAction: 'bedrockClientSend',
subActionParams: {
command,
signal: options?.abortSignal,
},
},
})) as {
data: ConverseResponse | ConverseStreamResponse;
status: string;
message?: string;
serviceMessage?: string;
};

if (data.status === 'error') {
throw new Error(
`ActionsClient BedrockRuntimeClient: action result status is error: ${data?.message} - ${data?.serviceMessage}`
);
}

return data.data;
}
}

This file was deleted.

This file was deleted.

9 changes: 5 additions & 4 deletions x-pack/packages/kbn-langchain/server/utils/bedrock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { finished } from 'stream/promises';
import { Logger } from '@kbn/core/server';
import { EventStreamCodec } from '@smithy/eventstream-codec';
import { fromUtf8, toUtf8 } from '@smithy/util-utf8';
import { Message } from '@aws-sdk/client-bedrock-runtime';
import { StreamParser } from './types';

export const parseBedrockStreamAsAsyncIterator = async function* (
Expand Down Expand Up @@ -227,7 +228,7 @@ function parseContent(content: Array<{ text?: string; type: string }>): string {
* Prepare messages for the bedrock API by combining messages from the same role
* @param messages
*/
export const prepareMessages = (messages: Array<{ role: string; content: string[] }>) =>
export const prepareMessages = (messages: Message[]) =>
messages.reduce((acc, { role, content }) => {
const lastMessage = acc[acc.length - 1];

Expand All @@ -236,13 +237,13 @@ export const prepareMessages = (messages: Array<{ role: string; content: string[
return acc;
}

if (lastMessage.role === role) {
acc[acc.length - 1].content = lastMessage.content.concat(content);
if (lastMessage.role === role && lastMessage.content) {
acc[acc.length - 1].content = lastMessage.content.concat(content || []);
return acc;
}

return acc;
}, [] as Array<{ role: string; content: string[] }>);
}, [] as Message[]);

export const DEFAULT_BEDROCK_MODEL = 'anthropic.claude-3-5-sonnet-20240620-v1:0';
export const DEFAULT_BEDROCK_REGION = 'us-east-1';
Loading