Giải thích đoạn code sau: [code]
- User
Giải thích đoạn code sau:
js - Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Giải thích đoạn code sau:
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
export async function POST(request: Request) {
const json = await request.json()
const { chatSettings, messages } = json as {
chatSettings: ChatSettings
messages: any[]
}
try {
const url = "https://nexra.aryahcr.cc/api/chat/complements"
const body = {
messages: messages,
stream: true,
markdown: false,
model: chatSettings.model
}
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(body)
})
if (!response.ok) {
return new Response(JSON.stringify({ message: response.statusText }), {
status: response.status
})
}
const reader = response.body?.getReader()
if (!reader) {
return new Response(JSON.stringify({ message: "No response body" }), {
status: 500
})
}
let previousMessage = ""
const encoder = new TextEncoder()
const readableStream = new ReadableStream({
async start(controller) {
try {
while (true) {
const { done, value } = await reader.read()
if (done) break
const text = new TextDecoder().decode(value)
console.log("Text:", text)
// Split on Record Separator and handle multiple chunks
const chunks = text.split("\u001e")
console.log("Chunks:", chunks)
for (let chunk of chunks) {
// Skip empty chunks
chunk = chunk.trim()
if (!chunk) continue
try {
const parsed = JSON.parse(chunk)
if (parsed.error) {
console.log("Error:", parsed.error)
return new Response(
JSON.stringify({ message: parsed.error }),
{
status: 500
}
)
}
// Only send the difference between current and previous message
if (parsed.message && parsed.message !== previousMessage) {
const newContent = parsed.message.slice(
previousMessage.length
)
controller.enqueue(encoder.encode(newContent))
previousMessage = parsed.message
}
if (parsed.finish) {
console.log("Finish:", parsed.finish)
controller.close()
return
}
} catch (e) {
console.log("Error parsing JSON:", e.message)
// Continue if JSON parse fails
continue
}
}
}
} catch (error) {
console.log("Error:", error)
controller.error(error)
}
}
})
return new Response(readableStream, {
headers: { "Content-Type": "text/plain" }
})
} catch (error: any) {
const errorMessage = error.message || "An unexpected error occurred"
const errorCode = error.status || 500
return new Response(JSON.stringify({ message: errorMessage }), {
status: errorCode
})
}
}
Đoạn mã bạn cung cấp là một hàm xử lý yêu cầu POST trong một ứng dụng Node.js, rất có thể là ứng dụng serverless hoặc sử dụng framework như Next.js. Dưới đây là phần giải thích cho từng phần của đoạn mã:
export async function POST(request: Request) {
Đây là một hàm async có tên POST, nó nhận một đối tượng request kiểu Request như tham số. Hàm này sẽ xử lý yêu cầu POST từ client.
const json = await request.json()
const { chatSettings, messages } = json as {
chatSettings: ChatSettings
messages: any[]
}
Hàm này đọc nội dung JSON từ yêu cầu và trích xuất chatSettings và messages từ đó. chatSettings có kiểu ChatSettings, và messages là một mảng các đối tượng không xác định (được đánh dấu là any[]).
const url = "https://nexra.aryahcr.cc/api/chat/complements"
const body = {
messages: messages,
stream: true,
markdown: false,
model: chatSettings.model
}
Hàm định nghĩa một URL mà sẽ gửi yêu cầu tiếp theo đến và xây dựng body cho yêu cầu POST, bao gồm danh sách tin nhắn, tùy chọn stream, không sử dụng markdown, và chỉ định mô hình từ chatSettings.
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(body)
})
Hàm gửi một yêu cầu POST sử dụng fetch đến URL định nghĩa trước đó với headers thông báo rằng nội dung là JSON và đưa body đã xây dựng vào trong thân yêu cầu.
if (!response.ok) {
return new Response(JSON.stringify({ message: response.statusText }), {
status: response.status
})
}
Nếu phản hồi không thành công (thông qua thuộc tính ok), hàm sẽ trả về một phản hồi mới với mã trạng thái và thông điệp phản hồi từ API.
const reader = response.body?.getReader()
if (!reader) {
return new Response(JSON.stringify({ message: "No response body" }), {
status: 500
})
}
//...
const readableStream = new ReadableStream({
async start(controller) {
try {
//...
} catch (error) {
controller.error(error)
}
}
})
Nếu phản hồi thành công, hàm lấy reader từ response.body để đọc dữ liệu từ phản hồi (có thể được gửi dưới dạng stream). Nếu không có body, nó trả về một thông báo lỗi.
Hàm tạo ra một ReadableStream với một hàm start, nơi sẽ đọc dữ liệu liên tục từ reader. Dữ liệu sẽ được đọc từng chunk, và mỗi chunk sẽ được mã hóa lại và gửi đến controller của stream.
while (true) {
const { done, value } = await reader.read();
if (done) break;
const text = new TextDecoder().decode(value);
// Split on Record Separator and handle multiple chunks
const chunks = text.split("\u001e");
//...
}
Ở đây, hàm đọc từng chunk và giải mã chúng thành văn bản, sau đó chia nhỏ văn bản thành các phần dựa trên ký tự phân tách (\u001e).
for (let chunk of chunks) {
// ...
}
Cho mỗi chunk, hàm sẽ loại bỏ các chunk rỗng, sau đó cố gắng phân tích cú pháp nó thành JSON. Nếu có lỗi hoặc nếu tin nhắn đã thay đổi, nó sẽ enque vào controller để gửi asynchronously cho client.
Cuối cùng, nếu tất cả suôn sẻ, hàm sẽ trả về một phản hồi với kiểu dữ liệu "text/plain".
Phần catch cuối cùng sẽ bắt mọi lỗi không mong muốn và trả về phản hồi lỗi với thông báo và trạng thái thích hợp.
Toàn bộ hàm này có vẻ như đang xử lý một luồng tin nhắn từ một API bên ngoài và cho phép client nhận các tin nhắn liên tục (được stream) từ đó.
Not yet included in a published release.