-
Notifications
You must be signed in to change notification settings - Fork 410
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Amazon Nova support via Bedrock (#1548)
- Loading branch information
Showing
13 changed files
with
995 additions
and
188 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
--- | ||
"@llamaindex/community": patch | ||
"docs": patch | ||
--- | ||
|
||
feat: Amazon Nova support via Bedrock |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,133 @@ | ||
import type { | ||
ContentBlockDelta, | ||
ConverseOutput, | ||
ConverseRequest, | ||
ConverseResponse, | ||
ConverseStreamOutput, | ||
InvokeModelCommandInput, | ||
InvokeModelWithResponseStreamCommandInput, | ||
ResponseStream, | ||
} from "@aws-sdk/client-bedrock-runtime"; | ||
import type { | ||
BaseTool, | ||
ChatMessage, | ||
LLMMetadata, | ||
ToolCall, | ||
ToolCallLLMMessageOptions, | ||
} from "@llamaindex/core/llms"; | ||
import { toUtf8 } from "../utils"; | ||
|
||
import { Provider, type BedrockChatStreamResponse } from "../provider"; | ||
import { | ||
mapBaseToolsToAmazonTools, | ||
mapChatMessagesToAmazonMessages, | ||
} from "./utils"; | ||
|
||
export class AmazonProvider extends Provider<ConverseStreamOutput> { | ||
getResultFromResponse(response: Record<string, any>): ConverseResponse { | ||
return JSON.parse(toUtf8(response.body)); | ||
} | ||
|
||
getToolsFromResponse<ToolContent>(response: ConverseOutput): ToolContent[] { | ||
return ( | ||
response.message?.content | ||
?.filter((item) => item.toolUse) | ||
.map( | ||
(item) => | ||
({ | ||
id: item.toolUse!.toolUseId, | ||
name: item.toolUse!.name, | ||
input: item.toolUse!.input | ||
? JSON.parse(item.toolUse!.input as string) | ||
: "", | ||
}) as ToolContent, | ||
) ?? [] | ||
); | ||
} | ||
|
||
getTextFromResponse(response: ConverseResponse): string { | ||
const result = this.getResultFromResponse(response); | ||
const content = result.output?.message?.content ?? []; | ||
return content.map((item) => item.text).join(" "); | ||
} | ||
|
||
getTextFromStreamResponse(response: ResponseStream): string { | ||
let event: ConverseStreamOutput | undefined = | ||
this.getStreamingEventResponse(response); | ||
if (!event || !event.contentBlockDelta) return ""; | ||
const delta: ContentBlockDelta | undefined = event.contentBlockDelta.delta; | ||
return delta?.text || ""; | ||
} | ||
|
||
async *reduceStream( | ||
stream: AsyncIterable<ResponseStream>, | ||
): BedrockChatStreamResponse { | ||
let toolId: string | undefined = undefined; | ||
let toolName: string | undefined = undefined; | ||
for await (const response of stream) { | ||
const event = this.getStreamingEventResponse(response); | ||
const delta = this.getTextFromStreamResponse(response); | ||
|
||
let options: undefined | ToolCallLLMMessageOptions = undefined; | ||
if (event?.contentBlockStart && event.contentBlockStart.start?.toolUse) { | ||
toolId = event.contentBlockStart.start?.toolUse.toolUseId; | ||
toolName = event.contentBlockStart.start?.toolUse.name; | ||
continue; | ||
} | ||
if ( | ||
toolId && | ||
toolName && | ||
event?.contentBlockDelta?.delta?.toolUse?.input | ||
) { | ||
options = { | ||
toolCall: [ | ||
{ | ||
id: toolId, | ||
name: toolName, | ||
input: JSON.parse(event?.contentBlockDelta?.delta?.toolUse.input), | ||
} as ToolCall, | ||
], | ||
}; | ||
toolId = undefined; | ||
toolName = undefined; | ||
} | ||
|
||
if (!delta && !options) continue; | ||
|
||
yield { | ||
delta: options ? "" : delta, | ||
options, | ||
raw: response, | ||
}; | ||
} | ||
} | ||
|
||
getRequestBody<T extends ChatMessage>( | ||
metadata: LLMMetadata, | ||
messages: T[], | ||
tools: BaseTool[] = [], | ||
options: Omit<ConverseRequest, "modelId" | "messages" | "inferenceConfig">, | ||
): InvokeModelCommandInput | InvokeModelWithResponseStreamCommandInput { | ||
const request: Omit<ConverseRequest, "modelId"> = { | ||
...options, | ||
messages: mapChatMessagesToAmazonMessages(messages), | ||
inferenceConfig: { | ||
maxTokens: metadata.maxTokens, | ||
temperature: metadata.temperature, | ||
topP: metadata.topP, | ||
}, | ||
}; | ||
if (tools.length) { | ||
request.toolConfig = { | ||
tools: mapBaseToolsToAmazonTools(tools), | ||
}; | ||
} | ||
|
||
return { | ||
modelId: metadata.model, | ||
contentType: "application/json", | ||
accept: "application/json", | ||
body: JSON.stringify(request), | ||
}; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
import type { ConverseRequest, Message } from "@aws-sdk/client-bedrock-runtime"; | ||
|
||
export type AmazonMessages = ConverseRequest["messages"]; | ||
|
||
export type AmazonMessage = Message; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,141 @@ | ||
import type { | ||
ImageBlock, | ||
ImageFormat, | ||
Message, | ||
Tool, | ||
} from "@aws-sdk/client-bedrock-runtime"; | ||
import type { | ||
BaseTool, | ||
ChatMessage, | ||
MessageContentDetail, | ||
ToolCallLLMMessageOptions, | ||
} from "@llamaindex/core/llms"; | ||
import { | ||
extractDataUrlComponents, | ||
mapMessageContentToMessageContentDetails, | ||
} from "../utils"; | ||
|
||
import type { JSONObject } from "@llamaindex/core/global"; | ||
import type { AmazonMessage, AmazonMessages } from "./types"; | ||
|
||
const ACCEPTED_IMAGE_MIME_TYPES = [ | ||
"image/jpeg", | ||
"image/png", | ||
"image/webp", | ||
"image/gif", | ||
] as const; | ||
|
||
const ACCEPTED_IMAGE_MIME_TYPE_FORMAT_MAP: Record< | ||
(typeof ACCEPTED_IMAGE_MIME_TYPES)[number], | ||
ImageFormat | ||
> = { | ||
"image/jpeg": "jpeg", | ||
"image/png": "png", | ||
"image/webp": "webp", | ||
"image/gif": "gif", | ||
}; | ||
|
||
export const mapImageContent = (imageUrl: string): ImageBlock => { | ||
if (!imageUrl.startsWith("data:")) | ||
throw new Error( | ||
"For Amazon please only use base64 data url, e.g.: data:image/jpeg;base64,SGVsbG8sIFdvcmxkIQ==", | ||
); | ||
const { mimeType, base64: data } = extractDataUrlComponents(imageUrl); | ||
if ( | ||
!ACCEPTED_IMAGE_MIME_TYPES.includes( | ||
mimeType as keyof typeof ACCEPTED_IMAGE_MIME_TYPE_FORMAT_MAP, | ||
) | ||
) | ||
throw new Error( | ||
`Amazon only accepts the following mimeTypes: ${ACCEPTED_IMAGE_MIME_TYPES.join("\n")}`, | ||
); | ||
|
||
return { | ||
format: | ||
ACCEPTED_IMAGE_MIME_TYPE_FORMAT_MAP[ | ||
mimeType as keyof typeof ACCEPTED_IMAGE_MIME_TYPE_FORMAT_MAP | ||
], | ||
|
||
// @ts-ignore: there's a mistake in the "@aws-sdk/client-bedrock-runtime" compared to the actual api | ||
source: { bytes: data }, | ||
}; | ||
}; | ||
|
||
export const mapMessageContentDetailToAmazonContent = < | ||
T extends MessageContentDetail, | ||
>( | ||
detail: T, | ||
): Message["content"] => { | ||
let content: Message["content"] = []; | ||
|
||
if (detail.type === "text") { | ||
content = [{ text: detail.text }]; | ||
} else if (detail.type === "image_url") { | ||
content = [{ image: mapImageContent(detail.image_url.url) }]; | ||
} else { | ||
throw new Error("Unsupported content detail type"); | ||
} | ||
return content; | ||
}; | ||
|
||
export const mapChatMessagesToAmazonMessages = < | ||
T extends ChatMessage<ToolCallLLMMessageOptions>, | ||
>( | ||
messages: T[], | ||
): AmazonMessages => { | ||
return messages.flatMap((msg: T): AmazonMessage[] => { | ||
return mapMessageContentToMessageContentDetails(msg.content).map( | ||
(detail: MessageContentDetail): AmazonMessage => { | ||
if (msg.options && "toolCall" in msg.options) { | ||
return { | ||
role: "assistant", | ||
content: msg.options.toolCall.map((call) => ({ | ||
toolUse: { | ||
toolUseId: call.id, | ||
name: call.name, | ||
input: call.input as JSONObject, | ||
}, | ||
})), | ||
}; | ||
} | ||
if (msg.options && "toolResult" in msg.options) { | ||
return { | ||
role: "user", | ||
content: [ | ||
{ | ||
toolResult: { | ||
toolUseId: msg.options.toolResult.id, | ||
content: [ | ||
{ | ||
text: msg.options.toolResult.result, | ||
}, | ||
], | ||
}, | ||
}, | ||
], | ||
}; | ||
} | ||
|
||
return { | ||
role: msg.role === "assistant" ? "assistant" : "user", | ||
content: mapMessageContentDetailToAmazonContent(detail), | ||
}; | ||
}, | ||
); | ||
}); | ||
}; | ||
|
||
export const mapBaseToolsToAmazonTools = (tools?: BaseTool[]): Tool[] => { | ||
if (!tools) return []; | ||
return tools.map((tool: BaseTool) => { | ||
const { | ||
metadata: { parameters, ...options }, | ||
} = tool; | ||
return { | ||
toolSpec: { | ||
...options, | ||
inputSchema: parameters, | ||
}, | ||
} as Tool; | ||
}); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.