-
Notifications
You must be signed in to change notification settings - Fork 61.2k
集成 AWS Bedrock 作为新的 LLM 服务提供商 #6430
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
Open
ac1982
wants to merge
7
commits into
ChatGPTNextWeb:main
Choose a base branch
from
ac1982:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
fc9688a
feat(bedrock): Integrate AWS Bedrock as a new LLM provider
78e8cb3
git yarn
04cbadb
Enhance API and Chat Actions with Improved Provider Handling
4093e4c
Improve AWS Bedrock Configuration Error Handling
a5caf98
Enhance Bedrock API Logging for Request Details
9a865fd
Update ChatActions to Assert Non-null Provider Name
3aae552
Refactor Bedrock API Configuration Check and Improve ChatActions Logging
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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 hidden or 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 hidden or 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 hidden or 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,249 @@ | ||
import { ModelProvider, Bedrock as BedrockConfig } from "@/app/constant"; | ||
import { getServerSideConfig } from "@/app/config/server"; | ||
import { prettyObject } from "@/app/utils/format"; | ||
import { NextRequest, NextResponse } from "next/server"; | ||
import { auth } from "../auth"; | ||
import { | ||
BedrockRuntimeClient, | ||
InvokeModelWithResponseStreamCommand, | ||
InvokeModelCommand, | ||
} from "@aws-sdk/client-bedrock-runtime"; | ||
|
||
const ALLOWED_PATH = new Set([BedrockConfig.ChatPath]); | ||
|
||
// Helper to get AWS Credentials | ||
function getAwsCredentials() { | ||
const config = getServerSideConfig(); | ||
if (!config.isBedrock) { | ||
throw new Error( | ||
"AWS Bedrock is not configured properly (ENABLE_AWS_BEDROCK is not true)", | ||
); | ||
} | ||
if (!config.bedrockAccessKeyId) { | ||
throw new Error("AWS Bedrock Access Key ID is missing or empty."); | ||
} | ||
if (!config.bedrockSecretAccessKey) { | ||
throw new Error("AWS Bedrock Secret Access Key is missing or empty."); | ||
} | ||
return { | ||
accessKeyId: config.bedrockAccessKeyId as string, | ||
secretAccessKey: config.bedrockSecretAccessKey as string, | ||
}; | ||
} | ||
|
||
export async function handle( | ||
req: NextRequest, | ||
{ params }: { params: { path: string[] } }, | ||
) { | ||
console.log("[Bedrock Route] params ", params); | ||
|
||
if (req.method === "OPTIONS") { | ||
return NextResponse.json({ body: "OK" }, { status: 200 }); | ||
} | ||
|
||
const subpath = params.path.join("/"); | ||
|
||
if (!ALLOWED_PATH.has(subpath)) { | ||
console.log("[Bedrock Route] forbidden path ", subpath); | ||
return NextResponse.json( | ||
{ error: true, msg: "you are not allowed to request " + subpath }, | ||
{ status: 403 }, | ||
); | ||
} | ||
|
||
// Auth check specifically for Bedrock (might not need header API key) | ||
const authResult = auth(req, ModelProvider.Bedrock); | ||
if (authResult.error) { | ||
return NextResponse.json(authResult, { status: 401 }); | ||
} | ||
|
||
try { | ||
const config = getServerSideConfig(); | ||
|
||
const bedrockRegion = config.bedrockRegion as string; | ||
const bedrockEndpoint = config.bedrockEndpoint; | ||
|
||
const client = new BedrockRuntimeClient({ | ||
region: bedrockRegion, | ||
credentials: getAwsCredentials(), | ||
endpoint: bedrockEndpoint || undefined, | ||
}); | ||
|
||
const body = await req.json(); | ||
console.log( | ||
"[Bedrock] Request - Model:", | ||
body.model, | ||
"Stream:", | ||
body.stream, | ||
"Messages count:", | ||
body.messages.length, | ||
); | ||
|
||
const { | ||
messages, | ||
model, | ||
stream = false, | ||
temperature = 0.7, | ||
max_tokens, | ||
} = body; | ||
|
||
// --- Payload formatting for Claude on Bedrock --- | ||
const isClaudeModel = model.includes("anthropic.claude"); | ||
if (!isClaudeModel) { | ||
return NextResponse.json( | ||
{ error: true, msg: "Unsupported Bedrock model: " + model }, | ||
{ status: 400 }, | ||
); | ||
} | ||
|
||
const systemPrompts = messages.filter((msg: any) => msg.role === "system"); | ||
const userAssistantMessages = messages.filter( | ||
(msg: any) => msg.role !== "system", | ||
); | ||
|
||
const payload = { | ||
anthropic_version: "bedrock-2023-05-31", | ||
max_tokens: max_tokens || 4096, | ||
temperature: temperature, | ||
messages: userAssistantMessages.map((msg: any) => ({ | ||
role: msg.role, // 'user' or 'assistant' | ||
content: | ||
typeof msg.content === "string" | ||
? [{ type: "text", text: msg.content }] | ||
: msg.content, // Assuming MultimodalContent format is compatible | ||
})), | ||
...(systemPrompts.length > 0 && { | ||
system: systemPrompts.map((msg: any) => msg.content).join("\n"), | ||
}), | ||
}; | ||
// --- End Payload Formatting --- | ||
|
||
if (stream) { | ||
const command = new InvokeModelWithResponseStreamCommand({ | ||
modelId: model, | ||
contentType: "application/json", | ||
accept: "application/json", | ||
body: JSON.stringify(payload), | ||
}); | ||
const response = await client.send(command); | ||
|
||
if (!response.body) { | ||
throw new Error("Empty response stream from Bedrock"); | ||
} | ||
const responseBody = response.body; | ||
|
||
const encoder = new TextEncoder(); | ||
const decoder = new TextDecoder(); | ||
const readableStream = new ReadableStream({ | ||
async start(controller) { | ||
try { | ||
for await (const event of responseBody) { | ||
if (event.chunk?.bytes) { | ||
const chunkData = JSON.parse(decoder.decode(event.chunk.bytes)); | ||
let responseText = ""; | ||
let finishReason: string | null = null; | ||
|
||
if ( | ||
chunkData.type === "content_block_delta" && | ||
chunkData.delta.type === "text_delta" | ||
) { | ||
responseText = chunkData.delta.text || ""; | ||
} else if (chunkData.type === "message_stop") { | ||
finishReason = | ||
chunkData["amazon-bedrock-invocationMetrics"] | ||
?.outputTokenCount > 0 | ||
? "stop" | ||
: "length"; // Example logic | ||
} | ||
|
||
// Format as OpenAI SSE chunk | ||
const sseData = { | ||
id: `chatcmpl-${nanoid()}`, | ||
object: "chat.completion.chunk", | ||
created: Math.floor(Date.now() / 1000), | ||
model: model, | ||
choices: [ | ||
{ | ||
index: 0, | ||
delta: { content: responseText }, | ||
finish_reason: finishReason, | ||
}, | ||
], | ||
}; | ||
controller.enqueue( | ||
encoder.encode(`data: ${JSON.stringify(sseData)}\n\n`), | ||
); | ||
|
||
if (finishReason) { | ||
controller.enqueue(encoder.encode("data: [DONE]\n\n")); | ||
break; // Exit loop after stop message | ||
} | ||
} | ||
} | ||
} catch (error) { | ||
console.error("[Bedrock] Streaming error:", error); | ||
controller.error(error); | ||
} finally { | ||
controller.close(); | ||
} | ||
}, | ||
}); | ||
|
||
return new NextResponse(readableStream, { | ||
headers: { | ||
"Content-Type": "text/event-stream", | ||
"Cache-Control": "no-cache", | ||
Connection: "keep-alive", | ||
}, | ||
}); | ||
} else { | ||
Comment on lines
+121
to
+199
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛠️ Refactor suggestion Handle partial chunk scenarios. |
||
// Non-streaming response | ||
const command = new InvokeModelCommand({ | ||
modelId: model, | ||
contentType: "application/json", | ||
accept: "application/json", | ||
body: JSON.stringify(payload), | ||
}); | ||
const response = await client.send(command); | ||
const responseBody = JSON.parse(new TextDecoder().decode(response.body)); | ||
|
||
// Format response to match OpenAI | ||
const formattedResponse = { | ||
id: `chatcmpl-${nanoid()}`, | ||
object: "chat.completion", | ||
created: Math.floor(Date.now() / 1000), | ||
model: model, | ||
choices: [ | ||
{ | ||
index: 0, | ||
message: { | ||
role: "assistant", | ||
content: responseBody.content?.[0]?.text ?? "", | ||
}, | ||
finish_reason: "stop", // Assuming stop for non-streamed | ||
}, | ||
], | ||
usage: { | ||
prompt_tokens: | ||
responseBody["amazon-bedrock-invocationMetrics"]?.inputTokenCount ?? | ||
-1, | ||
completion_tokens: | ||
responseBody["amazon-bedrock-invocationMetrics"] | ||
?.outputTokenCount ?? -1, | ||
total_tokens: | ||
(responseBody["amazon-bedrock-invocationMetrics"] | ||
?.inputTokenCount ?? 0) + | ||
(responseBody["amazon-bedrock-invocationMetrics"] | ||
?.outputTokenCount ?? 0) || -1, | ||
}, | ||
}; | ||
return NextResponse.json(formattedResponse); | ||
} | ||
} catch (e) { | ||
console.error("[Bedrock] API Handler Error:", e); | ||
return NextResponse.json(prettyObject(e), { status: 500 }); | ||
} | ||
} | ||
|
||
// Need nanoid for unique IDs | ||
import { nanoid } from "nanoid"; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Verify AWS credentials before returning.
This block immediately returns
{ error: false }
for Bedrock, skipping an explicit credential validation step. Consider ensuring that AWS credential checks (e.g., presence of required environment variables) have definitively passed before returning success.🧰 Tools
🪛 Biome (1.9.4)
[error] 104-104: Useless case clause.
because the default clause is present:
Unsafe fix: Remove the useless case.
(lint/complexity/noUselessSwitchCase)