Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🌐 chore: translate non-English comments to English in model-runtime/src/core/streams (#11506)

LobeHub Botdea1b25e2d3e
diff --git a/packages/model-runtime/src/core/streams/anthropic.ts b/packages/model-runtime/src/core/streams/anthropic.ts
index c0b02c18140..2d5f930222c 100644
--- a/packages/model-runtime/src/core/streams/anthropic.ts
+++ b/packages/model-runtime/src/core/streams/anthropic.ts
@@ -223,7 +223,7 @@ export const transformAnthropicStream = (
export interface AnthropicStreamOptions {
callbacks?: ChatStreamCallbacks;
- enableStreaming?: boolean; // 选择 TPS 计算方式(非流式时传 false)
+ enableStreaming?: boolean; // Select TPS calculation method (pass false for non-streaming)
inputStartAt?: number;
payload?: ChatPayloadForTransformStream;
}
diff --git a/packages/model-runtime/src/core/streams/google/index.ts b/packages/model-runtime/src/core/streams/google/index.ts
index 0776896d867..725f5c2924a 100644
--- a/packages/model-runtime/src/core/streams/google/index.ts
+++ b/packages/model-runtime/src/core/streams/google/index.ts
@@ -241,8 +241,8 @@ const transformGoogleGenerativeAIStream = (
{
data: {
citations: groundingChunks?.map((chunk) => ({
- // google 返回的 uri 是经过 google 自己处理过的 url,因此无法展现真实的 favicon
- // 需要使用 title 作为替换
+ // Google returns a uri processed by Google itself, so it cannot display the real favicon
+ // Need to use title as a replacement
favicon: chunk.web?.title,
title: chunk.web?.title,
url: chunk.web?.uri,
@@ -293,7 +293,7 @@ const transformGoogleGenerativeAIStream = (
...usageChunks,
].filter(Boolean) as StreamProtocolChunk[];
}
- // 当有 finishReason 但没有 text 内容时,发送一个空的 text 块以停止加载动画
+ // When there is finishReason but no text content, send an empty text chunk to stop the loading animation
return [
{ data: '', id: context?.id, type: 'text' },
{ data: candidate.finishReason, id: context?.id, type: 'stop' },
@@ -312,7 +312,7 @@ const transformGoogleGenerativeAIStream = (
export interface GoogleAIStreamOptions {
callbacks?: ChatStreamCallbacks;
- enableStreaming?: boolean; // 选择 TPS 计算方式(非流式时传 false)
+ enableStreaming?: boolean; // Select TPS calculation method (pass false for non-streaming)
inputStartAt?: number;
payload?: ChatPayloadForTransformStream;
}
diff --git a/packages/model-runtime/src/core/streams/model.ts b/packages/model-runtime/src/core/streams/model.ts
index 05c81ead016..b5433b0c95d 100644
--- a/packages/model-runtime/src/core/streams/model.ts
+++ b/packages/model-runtime/src/core/streams/model.ts
@@ -1,5 +1,5 @@
/**
- * 将异步迭代器转换为 JSON 格式的 ReadableStream
+ * Convert async iterator to JSON format ReadableStream
*/
export const createModelPullStream = <
T extends { completed?: number; digest?: string; status: string; total?: number },
@@ -7,48 +7,48 @@ export const createModelPullStream = <
iterable: AsyncIterable<T>,
model: string,
{
- onCancel, // 新增:取消时调用的回调函数
+ onCancel, // Added: callback function to call on cancellation
}: {
- onCancel?: (reason?: any) => void; // 回调函数签名
+ onCancel?: (reason?: any) => void; // Callback function signature
} = {},
): ReadableStream => {
- let iterator: AsyncIterator<T>; // 在外部跟踪迭代器以便取消时可以调用 return
+ let iterator: AsyncIterator<T>; // Track iterator externally so we can call return on cancellation
return new ReadableStream({
- // 实现 cancel 方法
+ // Implement cancel method
cancel(reason) {
- // 调用传入的 onCancel 回调,执行外部的清理逻辑(如 client.abort())
+ // Call the onCancel callback to execute external cleanup logic (e.g., client.abort())
if (onCancel) {
onCancel(reason);
}
- // 尝试优雅地终止迭代器
- // 注意:这依赖于 AsyncIterable 的实现是否支持 return/throw
+ // Attempt to gracefully terminate the iterator
+ // Note: This depends on whether the AsyncIterable implementation supports return/throw
if (iterator && typeof iterator.return === 'function') {
- // 不需要 await,让它在后台执行清理
+ // No need to await, let it execute cleanup in the background
iterator.return().catch();
}
},
async start(controller) {
- iterator = iterable[Symbol.asyncIterator](); // 获取迭代器
+ iterator = iterable[Symbol.asyncIterator](); // Get iterator
const encoder = new TextEncoder();
try {
// eslint-disable-next-line no-constant-condition
while (true) {
- // 等待下一个数据块或迭代完成
+ // Wait for the next data chunk or iteration completion
const { value: progress, done } = await iterator.next();
- // 如果迭代完成,跳出循环
+ // If iteration is complete, break the loop
if (done) {
break;
}
- // 忽略 'pulling manifest' 状态,因为它不包含进度
+ // Ignore 'pulling manifest' status as it does not contain progress
if (progress.status === 'pulling manifest') continue;
- // 格式化为标准格式并写入流
+ // Format to standard format and write to stream
const progressData =
JSON.stringify({
completed: progress.completed,
@@ -61,24 +61,24 @@ export const createModelPullStream = <
controller.enqueue(encoder.encode(progressData));
}
- // 正常完成
+ // Normal completion
controller.close();
} catch (error) {
- // 处理错误
+ // Handle errors
- // 如果错误是由于中止操作引起的,则静默处理或记录日志,然后尝试关闭流
+ // If error is caused by abort operation, handle silently or log, then try to close stream
if (error instanceof DOMException && error.name === 'AbortError') {
- // 不需要再 enqueue 错误信息,因为连接可能已断开
- // 尝试正常关闭,如果已经取消,controller 可能已关闭或出错
+ // No need to enqueue error message as connection may already be disconnected
+ // Try to close normally; if already cancelled, controller may be closed or errored
try {
controller.enqueue(new TextEncoder().encode(JSON.stringify({ status: 'cancelled' })));
controller.close();
} catch {
- // 忽略关闭错误,可能流已经被取消机制处理了
+ // Ignore close errors, stream may already be handled by cancellation mechanism
}
} else {
console.error('[createModelPullStream] model download stream error:', error);
- // 对于其他错误,尝试将错误信息发送给客户端
+ // For other errors, try to send error message to client
const errorMessage = error instanceof Error ? error.message : String(error);
const errorData =
JSON.stringify({
@@ -88,20 +88,20 @@ export const createModelPullStream = <
}) + '\n';
try {
- // 只有在流还期望数据时才尝试 enqueue
+ // Only try to enqueue if stream is still expecting data
if (controller.desiredSize !== null && controller.desiredSize > 0) {
controller.enqueue(encoder.encode(errorData));
}
} catch (enqueueError) {
console.error('[createModelPullStream] Error enqueueing error message:', enqueueError);
- // 如果这里也失败,很可能连接已断开
+ // If this also fails, connection is likely disconnected
}
- // 尝试关闭流或标记为错误状态
+ // Try to close stream or mark as error state
try {
- controller.close(); // 尝试正常关闭
+ controller.close(); // Try to close normally
} catch {
- controller.error(error); // 如果关闭失败,则将流置于错误状态
+ controller.error(error); // If closing fails, put stream in error state
}
}
}
diff --git a/packages/model-runtime/src/core/streams/ollama.ts b/packages/model-runtime/src/core/streams/ollama.ts
index 0e73f4da4db..c5ddd45b466 100644
--- a/packages/model-runtime/src/core/streams/ollama.ts
+++ b/packages/model-runtime/src/core/streams/ollama.ts
@@ -36,14 +36,14 @@ const transformOllamaStream = (chunk: ChatResponse, stack: StreamContext): Strea
return { data: 'finished', id: stack.id, type: 'stop' };
}
- // 判断是否有 <think> 或 </think> 标签,更新 thinkingInContent 状态
+ // Check for <think> or </think> tags and update thinkingInContent state
if (chunk.message.content.includes('<think>')) {
stack.thinkingInContent = true;
} else if (chunk.message.content.includes('</think>')) {
stack.thinkingInContent = false;
}
- // 清除 <think> 及 </think> 标签,并根据当前思考模式确定返回类型
+ // Remove <think> and </think> tags, and determine return type based on current thinking mode
return {
data: chunk.message.content.replaceAll(/<\/?think>/g, ''),
id: stack.id,
diff --git a/packages/model-runtime/src/core/streams/openai/openai.ts b/packages/model-runtime/src/core/streams/openai/openai.ts
index d5969e6fa67..541e9d5137e 100644
--- a/packages/model-runtime/src/core/streams/openai/openai.ts
+++ b/packages/model-runtime/src/core/streams/openai/openai.ts
@@ -88,8 +88,8 @@ const transformOpenAIStream = (
return { data: errorData, id: 'first_chunk_error', type: 'error' };
}
- // MiniMax 会在 base_resp 中返回业务错误(如余额不足),但不走 FIRST_CHUNK_ERROR_KEY
- // 典型返回:{ id: '...', choices: null, base_resp: { status_code: 1008, status_msg: 'insufficient balance' }, usage: {...} }
+ // MiniMax returns business errors (e.g., insufficient balance) in base_resp, but not through FIRST_CHUNK_ERROR_KEY
+ // Typical response: { id: '...', choices: null, base_resp: { status_code: 1008, status_msg: 'insufficient balance' }, usage: {...} }
if ((chunk as any).base_resp && typeof (chunk as any).base_resp.status_code === 'number') {
const baseResp = (chunk as any).base_resp as {
message?: string;
@@ -98,29 +98,29 @@ const transformOpenAIStream = (
};
if (baseResp.status_code !== 0) {
- // 根据 MiniMax 错误码映射到对应的错误类型
+ // Map MiniMax error codes to corresponding error types
let errorType: ILobeAgentRuntimeErrorType = AgentRuntimeErrorType.ProviderBizError;
switch (baseResp.status_code) {
- // 1004 - 未授权 / Token 不匹配 / 2049 - 无效的 API Key
+ // 1004 - Unauthorized / Token mismatch / 2049 - Invalid API Key
case 1004:
case 2049: {
errorType = AgentRuntimeErrorType.InvalidProviderAPIKey;
break;
}
- // 1008 - 余额不足
+ // 1008 - Insufficient balance
case 1008: {
errorType = AgentRuntimeErrorType.InsufficientQuota;
break;
}
- // 1002 - 请求频率超限 / 1041 - 连接数限制 / 2045 - 请求频率增长超限
+ // 1002 - Request rate limit exceeded / 1041 - Connection limit / 2045 - Request rate growth limit exceeded
case 1002:
case 1041:
case 2045: {
errorType = AgentRuntimeErrorType.QuotaLimitReached;
break;
}
- // 1039 - Token 限制
+ // 1039 - Token limit
case 1039: {
errorType = AgentRuntimeErrorType.ExceededContextWindow;
break;
diff --git a/packages/model-runtime/src/core/streams/protocol.ts b/packages/model-runtime/src/core/streams/protocol.ts
index 8c987c2f052..0d32285613c 100644
--- a/packages/model-runtime/src/core/streams/protocol.ts
+++ b/packages/model-runtime/src/core/streams/protocol.ts
@@ -402,25 +402,25 @@ export const createFirstErrorHandleTransformer = (
export const createSSEDataExtractor = () =>
new TransformStream({
transform(chunk: Uint8Array, controller) {
- // 将 Uint8Array 转换为字符串
+ // Convert Uint8Array to string
const text = new TextDecoder().decode(chunk, { stream: true });
- // 处理多行数据的情况
+ // Handle multi-line data case
const lines = text.split('\n');
for (const line of lines) {
- // 只处理以 "data: " 开头的行
+ // Only process lines starting with "data: "
if (line.startsWith('data: ')) {
- // 提取 "data: " 后面的实际数据
+ // Extract the actual data after "data: "
const jsonText = line.slice(6);
- // 跳过心跳消息
+ // Skip heartbeat messages
if (jsonText === '[DONE]') continue;
try {
- // 解析 JSON 数据
+ // Parse JSON data
const data = JSON.parse(jsonText);
- // 将解析后的数据传递给下一个处理器
+ // Pass parsed data to the next processor
controller.enqueue(data);
} catch {
console.warn('Failed to parse SSE data:', jsonText);
@@ -441,7 +441,7 @@ export const createTokenSpeedCalculator = (
{
inputStartAt,
streamStack,
- enableStreaming = true, // 选择 TPS 计算方式(非流式时传 false)
+ enableStreaming = true, // Select TPS calculation method (pass false for non-streaming)
}: { enableStreaming?: boolean; inputStartAt?: number; streamStack?: StreamContext } = {},
) => {
let outputStartAt: number | undefined;
diff --git a/packages/model-runtime/src/core/streams/spark.ts b/packages/model-runtime/src/core/streams/spark.ts
index b717f67d672..02605d116be 100644
--- a/packages/model-runtime/src/core/streams/spark.ts
+++ b/packages/model-runtime/src/core/streams/spark.ts
@@ -23,7 +23,7 @@ export function transformSparkResponseToStream(data: OpenAI.ChatCompletion) {
? Array.isArray(choice.message.tool_calls)
? choice.message.tool_calls
: [choice.message.tool_calls]
- : []; // 如果不是数组,包装成数组
+ : []; // If not an array, wrap it in an array
return {
delta: {
@@ -91,7 +91,7 @@ export const transformSparkStream = (chunk: OpenAI.ChatCompletionChunk): StreamP
if (item.delta?.tool_calls) {
const toolCallsArray = Array.isArray(item.delta.tool_calls)
? item.delta.tool_calls
- : [item.delta.tool_calls]; // 如果不是数组,包装成数组
+ : [item.delta.tool_calls]; // If not an array, wrap it in an array
if (toolCallsArray.length > 0) {
return {
@@ -108,7 +108,7 @@ export const transformSparkStream = (chunk: OpenAI.ChatCompletionChunk): StreamP
}
if (item.finish_reason) {
- // one-api 的流式接口,会出现既有 finish_reason ,也有 content 的情况
+ // one-api's streaming interface can have both finish_reason and content
// {"id":"demo","model":"deepl-en","choices":[{"index":0,"delta":{"role":"assistant","content":"Introduce yourself."},"finish_reason":"stop"}]}
if (typeof item.delta?.content === 'string' && !!item.delta.content) {
@@ -129,7 +129,7 @@ export const transformSparkStream = (chunk: OpenAI.ChatCompletionChunk): StreamP
if (typeof item.delta?.content === 'string') {
/*
- 处理 v1 endpoint usage,混合在最后一个 content 内容中
+ Handle v1 endpoint usage, mixed in the last content
{"code":0,"message":"Success","sid":"cha000d05ef@dx196553ae415b80a432","id":"cha000d05ef@dx196553ae415b80a432","created":1745186655,"choices":[{"delta":{"role":"assistant","content":"😊"},"index":0}],"usage":{"prompt_tokens":1,"completion_tokens":418,"total_tokens":419}}
*/
if (chunk.usage) {
@@ -146,7 +146,7 @@ export const transformSparkStream = (chunk: OpenAI.ChatCompletionChunk): StreamP
return { data: item.delta, id: chunk.id, type: 'data' };
}
- // 处理 v2 endpoint usage
+ // Handle v2 endpoint usage
if (chunk.usage) {
return { data: convertOpenAIUsage(chunk.usage), id: chunk.id, type: 'usage' };
}
diff --git a/packages/model-runtime/src/core/streams/vertex-ai.ts b/packages/model-runtime/src/core/streams/vertex-ai.ts
index d9f6acbe87b..93a92e9fe65 100644
--- a/packages/model-runtime/src/core/streams/vertex-ai.ts
+++ b/packages/model-runtime/src/core/streams/vertex-ai.ts
@@ -35,7 +35,7 @@ const transformVertexAIStream = (
}
if (
- candidate && // 首先检查是否为 reasoning 内容 (thought: true)
+ candidate && // First check if this is reasoning content (thought: true)
Array.isArray(candidate.content?.parts) &&
candidate.content.parts.length > 0
) {
@@ -88,8 +88,8 @@ const transformVertexAIStream = (
{
data: {
citations: groundingChunks?.map((chunk) => ({
- // google 返回的 uri 是经过 google 自己处理过的 url,因此无法展现真实的 favicon
- // 需要使用 title 作为替换
+ // Google returns a uri processed by Google itself, so it cannot display the real favicon
+ // Need to use title as a replacement
favicon: chunk.web?.title,
title: chunk.web?.title,
url: chunk.web?.uri,