Skip to content

Commit e791ac7

Browse files
committed
♻️ Translate error messages and Chinese comments in backend code into English #1131
1 parent ae952d6 commit e791ac7

File tree

9 files changed

+65
-52
lines changed

9 files changed

+65
-52
lines changed

backend/agents/create_agent_info.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ async def create_agent_config(
7979
is_manager=len(managed_agents) > 0, language=language)
8080

8181
# Get app information
82-
default_app_description = 'Nexent 是一个开源智能体SDK和平台' if language == 'zh' else 'Nexent is an open-source agent SDK and platform'
82+
default_app_description = 'Nexent is an open-source agent SDK and platform' if language == 'en' else 'Nexent 是一个开源智能体SDK和平台'
8383
app_name = tenant_config_manager.get_app_config(
8484
'APP_NAME', tenant_id=tenant_id) or "Nexent"
8585
app_description = tenant_config_manager.get_app_config(
@@ -132,7 +132,7 @@ async def create_agent_config(
132132
f"Failed to get summary for knowledge base {knowledge_name}: {e}")
133133
else:
134134
# TODO: Prompt should be refactored to yaml file
135-
knowledge_base_summary = "当前没有可用的知识库索引。\n" if language == 'zh' else "No knowledge base indexes are currently available.\n"
135+
knowledge_base_summary = "No knowledge base indexes are currently available.\n" if language == 'en' else "当前没有可用的知识库索引。\n"
136136
break # Only process the first KnowledgeBaseSearchTool found
137137
except Exception as e:
138138
logger.error(f"Failed to build knowledge base summary: {e}")

backend/apps/file_management_app.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -436,9 +436,9 @@ async def process_text_file(query, filename, file_content, tenant_id: str, langu
436436
result = response.json()
437437
raw_text = result.get("text", "")
438438
logger.info(
439-
f"File processed successfully: {raw_text[:200]}...{raw_text[-200:]}... length: {len(raw_text)}")
439+
f"File processed successfully: {raw_text[:200]}...{raw_text[-200:]}..., length: {len(raw_text)}")
440440
else:
441-
error_detail = response.json().get('detail', '未知错误') if response.headers.get(
441+
error_detail = response.json().get('detail', 'Unknown error') if response.headers.get(
442442
'content-type', '').startswith('application/json') else response.text
443443
logger.error(
444444
f"File processing failed (status code: {response.status_code}): {error_detail}")

backend/apps/model_managment_app.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,8 @@ async def create_provider_model(request: ProviderModelRequest, authorization: Op
115115
model_list = await get_provider_models(model_data)
116116

117117
# Merge existing model's max_tokens attribute
118-
model_list = merge_existing_model_tokens(model_list, tenant_id, request.provider, request.model_type)
118+
model_list = merge_existing_model_tokens(
119+
model_list, tenant_id, request.provider, request.model_type)
119120

120121
# Sort model list by ID
121122
model_list = sort_models_by_id(model_list)
@@ -164,7 +165,8 @@ async def batch_create_models(request: BatchCreateModelsRequest, authorization:
164165
existing_max_tokens = existing_model_by_display["max_tokens"]
165166
new_max_tokens = model["max_tokens"]
166167
if existing_max_tokens != new_max_tokens:
167-
update_model_record(existing_model_by_display["model_id"], {"max_tokens": new_max_tokens}, user_id)
168+
update_model_record(existing_model_by_display["model_id"], {
169+
"max_tokens": new_max_tokens}, user_id)
168170
continue
169171

170172
model_dict = await prepare_model_dict(
@@ -267,7 +269,7 @@ async def delete_model(display_name: str = Query(..., embed=True), authorization
267269
If the model is an embedding or multi_embedding type, both types will be deleted
268270
269271
Args:
270-
display_name: Display name of the model to delete (唯一键)
272+
display_name: Display name of the model to delete (unique key)
271273
authorization: Authorization header
272274
"""
273275
try:
@@ -282,10 +284,10 @@ async def delete_model(display_name: str = Query(..., embed=True), authorization
282284
message=f"Model not found: {display_name}",
283285
data=None
284286
)
285-
# 支持 embedding/multi_embedding 互删
287+
# Support mutual deletion of embedding/multi_embedding
286288
deleted_types = []
287289
if model["model_type"] in ["embedding", "multi_embedding"]:
288-
# 查找所有 embedding/multi_embedding 且 display_name 相同的模型
290+
# Find all embedding/multi_embedding models with the same display_name
289291
for t in ["embedding", "multi_embedding"]:
290292
m = get_model_by_display_name(display_name, tenant_id)
291293
if m and m["model_type"] == t:

backend/consts/model.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ def get_value(cls, status: Optional[str]) -> str:
2525
return status
2626

2727

28-
# 用户认证相关请求模型
28+
# User authentication related request models
2929
class UserSignUpRequest(BaseModel):
3030
"""User registration request model"""
3131
email: EmailStr

backend/database/utils.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
11
from typing import Any, Dict
22

33

4-
# 全局追踪字段管理方法
4+
# Global tracking field management methods
55
def add_creation_tracking(data: Dict[str, Any], user_id: str) -> Dict[str, Any]:
66
"""
7-
添加创建追踪字段(created_by和updated_by)
7+
Add creation tracking fields (created_by and updated_by)
88
99
Args:
10-
data: 要添加字段的数据字典
11-
user_id: 当前用户ID
10+
data: Data dictionary to add fields to
11+
user_id: Current user ID
1212
1313
Returns:
14-
Dict[str, Any]: 添加追踪字段后的数据字典
14+
Dict[str, Any]: Data dictionary with tracking fields added
1515
"""
1616
data_copy = data.copy()
1717
data_copy["created_by"] = user_id
@@ -21,14 +21,14 @@ def add_creation_tracking(data: Dict[str, Any], user_id: str) -> Dict[str, Any]:
2121

2222
def add_update_tracking(data: Dict[str, Any], user_id: str) -> Dict[str, Any]:
2323
"""
24-
添加更新追踪字段(updated_by
24+
Add update tracking field (updated_by)
2525
2626
Args:
27-
data: 要添加字段的数据字典
28-
user_id: 当前用户ID
27+
data: Data dictionary to add field to
28+
user_id: Current user ID
2929
3030
Returns:
31-
Dict[str, Any]: 添加追踪字段后的数据字典
31+
Dict[str, Any]: Data dictionary with tracking field added
3232
"""
3333
data_copy = data.copy()
3434
data_copy["updated_by"] = user_id

backend/services/data_process_service.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,8 @@ def _init_redis_client(self):
6565
connection_pool=self.redis_pool)
6666
logger.info("Redis client initialized successfully.")
6767
else:
68-
logger.warning("REDIS_BACKEND_URL not set, Redis client not initialized.")
68+
logger.warning(
69+
"REDIS_BACKEND_URL not set, Redis client not initialized.")
6970
except Exception as e:
7071
logger.error(f"Failed to initialize Redis client: {str(e)}")
7172

@@ -82,7 +83,8 @@ def _init_clip_model(self):
8283
self.clip_available = True
8384
logger.info("CLIP model loaded successfully")
8485
except Exception as e:
85-
logger.warning(f"Failed to load CLIP model, size-only filtering will be used: {str(e)}")
86+
logger.warning(
87+
f"Failed to load CLIP model, size-only filtering will be used: {str(e)}")
8688
self.clip_available = False
8789

8890
async def start(self):
@@ -102,7 +104,8 @@ def _get_celery_inspector(self):
102104
if not celery_app.conf.broker_url or not celery_app.conf.result_backend:
103105
celery_app.conf.broker_url = REDIS_URL
104106
celery_app.conf.result_backend = REDIS_BACKEND_URL
105-
logger.warning(f"Celery broker URL is not configured properly, reconfiguring to {celery_app.conf.broker_url}")
107+
logger.warning(
108+
f"Celery broker URL is not configured properly, reconfiguring to {celery_app.conf.broker_url}")
106109
try:
107110
inspector = celery_app.control.inspect()
108111
inspector.ping()
@@ -176,8 +179,10 @@ def get_reserved():
176179
# Add to the set, duplicates will be handled
177180
task_ids.add(task_id)
178181
except Exception as redis_error:
179-
logger.warning(f"Failed to query Redis for stored task IDs: {str(redis_error)}")
180-
logger.debug(f"Total unique task IDs collected (inspector + Redis): {len(task_ids)}")
182+
logger.warning(
183+
f"Failed to query Redis for stored task IDs: {str(redis_error)}")
184+
logger.debug(
185+
f"Total unique task IDs collected (inspector + Redis): {len(task_ids)}")
181186
tasks = [get_task_info(task_id) for task_id in task_ids]
182187
all_task_infos = await asyncio.gather(*tasks, return_exceptions=True)
183188
for task_info in all_task_infos:
@@ -366,7 +371,7 @@ async def filter_important_image(self, image_url: str, positive_prompt: str = "a
366371
}
367372
}
368373

369-
# 延迟加载CLIP模型
374+
# Lazy load CLIP model
370375
if not self.clip_available:
371376
self._init_clip_model()
372377

backend/services/prompt_service.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -237,8 +237,8 @@ def _stream_results(produce_queue, latest, stop_flags, threads):
237237

238238

239239
def join_info_for_generate_system_prompt(prompt_for_generate, sub_agent_info_list, task_description, tool_info_list, language: str = 'zh'):
240-
input_label = "接受输入" if language == 'zh' else "Inputs"
241-
output_label = "返回输出类型" if language == 'zh' else "Output type"
240+
input_label = "Inputs" if language == 'en' else "接受输入"
241+
output_label = "Output type" if language == 'en' else "返回输出类型"
242242

243243
tool_description = "\n".join(
244244
[f"- {tool['name']}: {tool['description']} \n {input_label}: {tool['inputs']}\n {output_label}: {tool['output_type']}"

backend/utils/auth_utils.py

Lines changed: 30 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
# Get Supabase configuration
1717
SUPABASE_URL = os.getenv('SUPABASE_URL', 'http://118.31.249.152:8010')
1818
SUPABASE_KEY = os.getenv('SUPABASE_KEY', '')
19-
# 调试用 JWT 过期时间(秒),未设置或为 0 表示不生效
19+
# Debug JWT expiration time (seconds), not set or 0 means not effective
2020
DEBUG_JWT_EXPIRE_SECONDS = int(os.getenv('DEBUG_JWT_EXPIRE_SECONDS', '0') or 0)
2121

2222
# Module logger
@@ -115,7 +115,8 @@ def verify_aksk_signature(
115115
raise SignatureValidationError("Timestamp is invalid or expired")
116116

117117
# TODO: get ak/sk according to tenant_id from DB
118-
mock_access_key, mock_secret_key = get_aksk_config(tenant_id="tenant_id")
118+
mock_access_key, mock_secret_key = get_aksk_config(
119+
tenant_id="tenant_id")
119120

120121
if access_key != mock_access_key:
121122
logger.warning(f"Invalid access key: {access_key}")
@@ -199,62 +200,64 @@ def validate_aksk_authentication(headers: dict, request_body: str = "") -> bool:
199200
logger.error(f"Unexpected error during AK/SK authentication: {e}")
200201
raise UnauthorizedError("Authentication failed")
201202

203+
202204
def get_supabase_client():
203205
"""Get Supabase client instance"""
204206
try:
205207
return create_client(SUPABASE_URL, SUPABASE_KEY)
206208
except Exception as e:
207-
logging.error(f"创建Supabase客户端失败: {str(e)}")
209+
logging.error(f"Failed to create Supabase client: {str(e)}")
208210
return None
209211

210212

211213
def get_jwt_expiry_seconds(token: str) -> int:
212214
"""
213-
从JWT令牌中获取过期时间(秒)
215+
Get expiration time from JWT token (seconds)
214216
215217
Args:
216-
token: JWT令牌字符串
218+
token: JWT token string
217219
218220
Returns:
219-
int: 令牌的有效期(秒),如果解析失败则返回默认值3600
221+
int: Token validity period (seconds), returns default value 3600 if parsing fails
220222
"""
221223
try:
222224
# Speed mode: treat sessions as never expiring
223225
if IS_SPEED_MODE:
224226
# 10 years in seconds
225227
return 10 * 365 * 24 * 60 * 60
226-
# 确保token是纯JWT,去除可能的Bearer前缀
227-
jwt_token = token.replace("Bearer ", "") if token.startswith("Bearer ") else token
228+
# Ensure token is pure JWT, remove possible Bearer prefix
229+
jwt_token = token.replace(
230+
"Bearer ", "") if token.startswith("Bearer ") else token
228231

229-
# 如果设置了调试过期时间,直接返回以便快速调试
232+
# If debug expiration time is set, return directly for quick debugging
230233
if DEBUG_JWT_EXPIRE_SECONDS > 0:
231234
return DEBUG_JWT_EXPIRE_SECONDS
232235

233-
# 解码JWT令牌(不验证签名,只解析内容)
236+
# Decode JWT token (without signature verification, only parse content)
234237
decoded = jwt.decode(jwt_token, options={"verify_signature": False})
235238

236-
# 从JWT声明中提取过期时间和签发时间
239+
# Extract expiration time and issued time from JWT claims
237240
exp = decoded.get("exp", 0)
238241
iat = decoded.get("iat", 0)
239242

240-
# 计算有效期(秒)
243+
# Calculate validity period (seconds)
241244
expiry_seconds = exp - iat
242245

243246
return expiry_seconds
244247
except Exception as e:
245-
logging.warning(f"从令牌获取过期时间失败: {str(e)}")
246-
return 3600 # supabase默认设置
248+
logging.warning(f"Failed to get expiration time from token: {str(e)}")
249+
return 3600 # supabase default setting
247250

248251

249252
def calculate_expires_at(token: Optional[str] = None) -> int:
250253
"""
251-
计算会话过期时间(与Supabase JWT过期时间保持一致)
254+
Calculate session expiration time (consistent with Supabase JWT expiration time)
252255
253256
Args:
254-
token: 可选的JWT令牌,用于获取实际过期时间
257+
token: Optional JWT token to get actual expiration time
255258
256259
Returns:
257-
int: 过期时间的时间戳
260+
int: Expiration time timestamp
258261
"""
259262
# Speed mode: far future expiration
260263
if IS_SPEED_MODE:
@@ -275,13 +278,14 @@ def _extract_user_id_from_jwt_token(authorization: str) -> Optional[str]:
275278
Optional[str]: User ID, return None if parsing fails
276279
"""
277280
try:
278-
# 格式化授权头部
279-
token = authorization.replace("Bearer ", "") if authorization.startswith("Bearer ") else authorization
281+
# Format authorization header
282+
token = authorization.replace("Bearer ", "") if authorization.startswith(
283+
"Bearer ") else authorization
280284

281-
# 解码JWT令牌(不验证签名,只解析内容)
285+
# Decode JWT token (without signature verification, only parse content)
282286
decoded = jwt.decode(token, options={"verify_signature": False})
283287

284-
# 从JWT声明中提取用户ID
288+
# Extract user ID from JWT claims
285289
user_id = decoded.get("sub")
286290

287291
return user_id
@@ -302,7 +306,8 @@ def get_current_user_id(authorization: Optional[str] = None) -> tuple[str, str]:
302306
"""
303307
# if deploy in speed mode or authorization is None, return default user id and tenant id
304308
if IS_SPEED_MODE or authorization is None:
305-
logging.debug("Speed mode or no valid authorization header detected - returning default user ID and tenant ID")
309+
logging.debug(
310+
"Speed mode or no valid authorization header detected - returning default user ID and tenant ID")
306311
return DEFAULT_USER_ID, DEFAULT_TENANT_ID
307312

308313
try:
@@ -316,12 +321,13 @@ def get_current_user_id(authorization: Optional[str] = None) -> tuple[str, str]:
316321
logging.debug(f"Found tenant ID for user {user_id}: {tenant_id}")
317322
else:
318323
tenant_id = DEFAULT_TENANT_ID
319-
logging.warning(f"No tenant relationship found for user {user_id}, using default tenant")
324+
logging.warning(
325+
f"No tenant relationship found for user {user_id}, using default tenant")
320326

321327
return user_id, tenant_id
322328

323329
except Exception as e:
324-
logging.error(f"Failed to get user ID and tanent ID: {str(e)}")
330+
logging.error(f"Failed to get user ID and tenant ID: {str(e)}")
325331
raise UnauthorizedError("Invalid or expired authentication token")
326332

327333

backend/utils/prompt_template_utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ def get_prompt_template(template_type: str, language: str = 'zh', **kwargs) -> D
2222
dict: Loaded prompt template
2323
"""
2424
logger.info(
25-
f"Getting prompt template for type: {template_type}, language: {language}kwargs: {kwargs}")
25+
f"Getting prompt template for type: {template_type}, language: {language}, kwargs: {kwargs}")
2626

2727
# Define template path mapping
2828
template_paths = {

0 commit comments

Comments
 (0)