diff --git a/backend/app/api/graph.py b/backend/app/api/graph.py
index 12ff1ba2d..5e1d9dc23 100644
--- a/backend/app/api/graph.py
+++ b/backend/app/api/graph.py
@@ -42,9 +42,9 @@ def get_project(project_id: str):
if not project:
return jsonify({
"success": False,
- "error": f"项目不存在: {project_id}"
+ "error": f"Project not found: {project_id}"
}), 404
-
+
return jsonify({
"success": True,
"data": project.to_dict()
@@ -76,12 +76,12 @@ def delete_project(project_id: str):
if not success:
return jsonify({
"success": False,
- "error": f"项目不存在或删除失败: {project_id}"
+ "error": f"Project not found or deletion failed: {project_id}"
}), 404
-
+
return jsonify({
"success": True,
- "message": f"项目已删除: {project_id}"
+ "message": f"Project deleted: {project_id}"
})
@@ -95,9 +95,9 @@ def reset_project(project_id: str):
if not project:
return jsonify({
"success": False,
- "error": f"项目不存在: {project_id}"
+ "error": f"Project not found: {project_id}"
}), 404
-
+
# 重置到本体已生成状态
if project.ontology:
project.status = ProjectStatus.ONTOLOGY_GENERATED
@@ -111,7 +111,7 @@ def reset_project(project_id: str):
return jsonify({
"success": True,
- "message": f"项目已重置: {project_id}",
+ "message": f"Project reset: {project_id}",
"data": project.to_dict()
})
@@ -160,7 +160,7 @@ def generate_ontology():
if not simulation_requirement:
return jsonify({
"success": False,
- "error": "请提供模拟需求描述 (simulation_requirement)"
+ "error": "Please provide simulation requirement description (simulation_requirement)"
}), 400
# 获取上传的文件
@@ -168,7 +168,7 @@ def generate_ontology():
if not uploaded_files or all(not f.filename for f in uploaded_files):
return jsonify({
"success": False,
- "error": "请至少上传一个文档文件"
+ "error": "Please upload at least one document file"
}), 400
# 创建项目
@@ -203,7 +203,7 @@ def generate_ontology():
ProjectManager.delete_project(project.project_id)
return jsonify({
"success": False,
- "error": "没有成功处理任何文档,请检查文件格式"
+ "error": "No documents were successfully processed, please check the file format"
}), 400
# 保存提取的文本
@@ -285,12 +285,12 @@ def build_graph():
# 检查配置
errors = []
if not Config.ZEP_API_KEY:
- errors.append("ZEP_API_KEY未配置")
+ errors.append("ZEP_API_KEY not configured")
if errors:
logger.error(f"配置错误: {errors}")
return jsonify({
"success": False,
- "error": "配置错误: " + "; ".join(errors)
+ "error": "Configuration error: " + "; ".join(errors)
}), 500
# 解析请求
@@ -301,15 +301,15 @@ def build_graph():
if not project_id:
return jsonify({
"success": False,
- "error": "请提供 project_id"
+ "error": "Please provide project_id"
}), 400
-
+
# 获取项目
project = ProjectManager.get_project(project_id)
if not project:
return jsonify({
"success": False,
- "error": f"项目不存在: {project_id}"
+ "error": f"Project not found: {project_id}"
}), 404
# 检查项目状态
@@ -318,13 +318,13 @@ def build_graph():
if project.status == ProjectStatus.CREATED:
return jsonify({
"success": False,
- "error": "项目尚未生成本体,请先调用 /ontology/generate"
+ "error": "Project has no ontology yet, please call /ontology/generate first"
}), 400
if project.status == ProjectStatus.GRAPH_BUILDING and not force:
return jsonify({
"success": False,
- "error": "图谱正在构建中,请勿重复提交。如需强制重建,请添加 force: true",
+ "error": "Graph is already being built, do not resubmit. To force rebuild, add force: true",
"task_id": project.graph_build_task_id
}), 400
@@ -349,7 +349,7 @@ def build_graph():
if not text:
return jsonify({
"success": False,
- "error": "未找到提取的文本内容"
+ "error": "No extracted text content found"
}), 400
# 获取本体
@@ -357,7 +357,7 @@ def build_graph():
if not ontology:
return jsonify({
"success": False,
- "error": "未找到本体定义"
+ "error": "No ontology definition found"
}), 400
# 创建异步任务
@@ -378,7 +378,7 @@ def build_task():
task_manager.update_task(
task_id,
status=TaskStatus.PROCESSING,
- message="初始化图谱构建服务..."
+ message="Initializing graph build service..."
)
# 创建图谱构建服务
@@ -387,7 +387,7 @@ def build_task():
# 分块
task_manager.update_task(
task_id,
- message="文本分块中...",
+ message="Chunking text...",
progress=5
)
chunks = TextProcessor.split_text(
@@ -400,7 +400,7 @@ def build_task():
# 创建图谱
task_manager.update_task(
task_id,
- message="创建Zep图谱...",
+ message="Creating Zep graph...",
progress=10
)
graph_id = builder.create_graph(name=graph_name)
@@ -412,7 +412,7 @@ def build_task():
# 设置本体
task_manager.update_task(
task_id,
- message="设置本体定义...",
+ message="Setting ontology definition...",
progress=15
)
builder.set_ontology(graph_id, ontology)
@@ -428,7 +428,7 @@ def add_progress_callback(msg, progress_ratio):
task_manager.update_task(
task_id,
- message=f"开始添加 {total_chunks} 个文本块...",
+ message=f"Starting to add {total_chunks} text chunks...",
progress=15
)
@@ -442,7 +442,7 @@ def add_progress_callback(msg, progress_ratio):
# 等待Zep处理完成(查询每个episode的processed状态)
task_manager.update_task(
task_id,
- message="等待Zep处理数据...",
+ message="Waiting for Zep to process data...",
progress=55
)
@@ -459,7 +459,7 @@ def wait_progress_callback(msg, progress_ratio):
# 获取图谱数据
task_manager.update_task(
task_id,
- message="获取图谱数据...",
+ message="Retrieving graph data...",
progress=95
)
graph_data = builder.get_graph_data(graph_id)
@@ -476,7 +476,7 @@ def wait_progress_callback(msg, progress_ratio):
task_manager.update_task(
task_id,
status=TaskStatus.COMPLETED,
- message="图谱构建完成",
+ message="Graph build complete",
progress=100,
result={
"project_id": project_id,
@@ -499,7 +499,7 @@ def wait_progress_callback(msg, progress_ratio):
task_manager.update_task(
task_id,
status=TaskStatus.FAILED,
- message=f"构建失败: {str(e)}",
+ message=f"Build failed: {str(e)}",
error=traceback.format_exc()
)
@@ -512,7 +512,7 @@ def wait_progress_callback(msg, progress_ratio):
"data": {
"project_id": project_id,
"task_id": task_id,
- "message": "图谱构建任务已启动,请通过 /task/{task_id} 查询进度"
+ "message": "Graph build task started, check progress via /task/{task_id}"
}
})
@@ -536,7 +536,7 @@ def get_task(task_id: str):
if not task:
return jsonify({
"success": False,
- "error": f"任务不存在: {task_id}"
+ "error": f"Task not found: {task_id}"
}), 404
return jsonify({
@@ -570,7 +570,7 @@ def get_graph_data(graph_id: str):
if not Config.ZEP_API_KEY:
return jsonify({
"success": False,
- "error": "ZEP_API_KEY未配置"
+ "error": "ZEP_API_KEY not configured"
}), 500
builder = GraphBuilderService(api_key=Config.ZEP_API_KEY)
@@ -598,7 +598,7 @@ def delete_graph(graph_id: str):
if not Config.ZEP_API_KEY:
return jsonify({
"success": False,
- "error": "ZEP_API_KEY未配置"
+ "error": "ZEP_API_KEY not configured"
}), 500
builder = GraphBuilderService(api_key=Config.ZEP_API_KEY)
@@ -606,7 +606,7 @@ def delete_graph(graph_id: str):
return jsonify({
"success": True,
- "message": f"图谱已删除: {graph_id}"
+ "message": f"Graph deleted: {graph_id}"
})
except Exception as e:
diff --git a/backend/app/api/report.py b/backend/app/api/report.py
index e05c73c39..0b8a79a38 100644
--- a/backend/app/api/report.py
+++ b/backend/app/api/report.py
@@ -53,19 +53,19 @@ def generate_report():
if not simulation_id:
return jsonify({
"success": False,
- "error": "请提供 simulation_id"
+ "error": "Please provide simulation_id"
}), 400
-
+
force_regenerate = data.get('force_regenerate', False)
-
+
# 获取模拟信息
manager = SimulationManager()
state = manager.get_simulation(simulation_id)
-
+
if not state:
return jsonify({
"success": False,
- "error": f"模拟不存在: {simulation_id}"
+ "error": f"Simulation not found: {simulation_id}"
}), 404
# 检查是否已有报告
@@ -78,7 +78,7 @@ def generate_report():
"simulation_id": simulation_id,
"report_id": existing_report.report_id,
"status": "completed",
- "message": "报告已存在",
+ "message": "Report already exists",
"already_generated": True
}
})
@@ -88,21 +88,21 @@ def generate_report():
if not project:
return jsonify({
"success": False,
- "error": f"项目不存在: {state.project_id}"
+ "error": f"Project not found: {state.project_id}"
}), 404
-
+
graph_id = state.graph_id or project.graph_id
if not graph_id:
return jsonify({
"success": False,
- "error": "缺少图谱ID,请确保已构建图谱"
+ "error": "Missing graph ID, please ensure graph has been built"
}), 400
simulation_requirement = project.simulation_requirement
if not simulation_requirement:
return jsonify({
"success": False,
- "error": "缺少模拟需求描述"
+ "error": "Missing simulation requirement description"
}), 400
# 提前生成 report_id,以便立即返回给前端
@@ -127,7 +127,7 @@ def run_generate():
task_id,
status=TaskStatus.PROCESSING,
progress=0,
- message="初始化Report Agent..."
+ message="Initializing Report Agent..."
)
# 创建Report Agent
@@ -164,7 +164,7 @@ def progress_callback(stage, progress, message):
}
)
else:
- task_manager.fail_task(task_id, report.error or "报告生成失败")
+ task_manager.fail_task(task_id, report.error or "Report generation failed")
except Exception as e:
logger.error(f"报告生成失败: {str(e)}")
@@ -181,7 +181,7 @@ def progress_callback(stage, progress, message):
"report_id": report_id,
"task_id": task_id,
"status": "generating",
- "message": "报告生成任务已启动,请通过 /api/report/generate/status 查询进度",
+ "message": "Report generation task started, check progress via /api/report/generate/status",
"already_generated": False
}
})
@@ -234,7 +234,7 @@ def get_generate_status():
"report_id": existing_report.report_id,
"status": "completed",
"progress": 100,
- "message": "报告已生成",
+ "message": "Report already generated",
"already_completed": True
}
})
@@ -242,16 +242,16 @@ def get_generate_status():
if not task_id:
return jsonify({
"success": False,
- "error": "请提供 task_id 或 simulation_id"
+ "error": "Please provide task_id or simulation_id"
}), 400
-
+
task_manager = TaskManager()
task = task_manager.get_task(task_id)
-
+
if not task:
return jsonify({
"success": False,
- "error": f"任务不存在: {task_id}"
+ "error": f"Task not found: {task_id}"
}), 404
return jsonify({
@@ -294,7 +294,7 @@ def get_report(report_id: str):
if not report:
return jsonify({
"success": False,
- "error": f"报告不存在: {report_id}"
+ "error": f"Report not found: {report_id}"
}), 404
return jsonify({
@@ -331,7 +331,7 @@ def get_report_by_simulation(simulation_id: str):
if not report:
return jsonify({
"success": False,
- "error": f"该模拟暂无报告: {simulation_id}",
+ "error": f"No report for this simulation: {simulation_id}",
"has_report": False
}), 404
@@ -403,7 +403,7 @@ def download_report(report_id: str):
if not report:
return jsonify({
"success": False,
- "error": f"报告不存在: {report_id}"
+ "error": f"Report not found: {report_id}"
}), 404
md_path = ReportManager._get_report_markdown_path(report_id)
@@ -445,12 +445,12 @@ def delete_report(report_id: str):
if not success:
return jsonify({
"success": False,
- "error": f"报告不存在: {report_id}"
+ "error": f"Report not found: {report_id}"
}), 404
return jsonify({
"success": True,
- "message": f"报告已删除: {report_id}"
+ "message": f"Report deleted: {report_id}"
})
except Exception as e:
@@ -501,13 +501,13 @@ def chat_with_report_agent():
if not simulation_id:
return jsonify({
"success": False,
- "error": "请提供 simulation_id"
+ "error": "Please provide simulation_id"
}), 400
-
+
if not message:
return jsonify({
"success": False,
- "error": "请提供 message"
+ "error": "Please provide message"
}), 400
# 获取模拟和项目信息
@@ -517,21 +517,21 @@ def chat_with_report_agent():
if not state:
return jsonify({
"success": False,
- "error": f"模拟不存在: {simulation_id}"
+ "error": f"Simulation not found: {simulation_id}"
}), 404
-
+
project = ProjectManager.get_project(state.project_id)
if not project:
return jsonify({
"success": False,
- "error": f"项目不存在: {state.project_id}"
+ "error": f"Project not found: {state.project_id}"
}), 404
graph_id = state.graph_id or project.graph_id
if not graph_id:
return jsonify({
"success": False,
- "error": "缺少图谱ID"
+ "error": "Missing graph ID"
}), 400
simulation_requirement = project.simulation_requirement or ""
@@ -585,7 +585,7 @@ def get_report_progress(report_id: str):
if not progress:
return jsonify({
"success": False,
- "error": f"报告不存在或进度信息不可用: {report_id}"
+ "error": f"Report not found or progress not available: {report_id}"
}), 404
return jsonify({
@@ -673,7 +673,7 @@ def get_single_section(report_id: str, section_index: int):
if not os.path.exists(section_path):
return jsonify({
"success": False,
- "error": f"章节不存在: section_{section_index:02d}.md"
+ "error": f"Section not found: section_{section_index:02d}.md"
}), 404
with open(section_path, 'r', encoding='utf-8') as f:
@@ -949,7 +949,7 @@ def search_graph_tool():
if not graph_id or not query:
return jsonify({
"success": False,
- "error": "请提供 graph_id 和 query"
+ "error": "Please provide graph_id and query"
}), 400
from ..services.zep_tools import ZepToolsService
@@ -993,7 +993,7 @@ def get_graph_statistics_tool():
if not graph_id:
return jsonify({
"success": False,
- "error": "请提供 graph_id"
+ "error": "Please provide graph_id"
}), 400
from ..services.zep_tools import ZepToolsService
diff --git a/backend/app/api/simulation.py b/backend/app/api/simulation.py
index 3a0f68168..fe1ec61fe 100644
--- a/backend/app/api/simulation.py
+++ b/backend/app/api/simulation.py
@@ -21,7 +21,7 @@
# Interview prompt 优化前缀
# 添加此前缀可以避免Agent调用工具,直接用文本回复
-INTERVIEW_PROMPT_PREFIX = "结合你的人设、所有的过往记忆与行动,不调用任何工具直接用文本回复我:"
+INTERVIEW_PROMPT_PREFIX = "Based on your persona, all past memories and actions, reply to me directly in text without calling any tools: "
def optimize_interview_prompt(prompt: str) -> str:
@@ -59,9 +59,9 @@ def get_graph_entities(graph_id: str):
if not Config.ZEP_API_KEY:
return jsonify({
"success": False,
- "error": "ZEP_API_KEY未配置"
+ "error": "ZEP_API_KEY not configured"
}), 500
-
+
entity_types_str = request.args.get('entity_types', '')
entity_types = [t.strip() for t in entity_types_str.split(',') if t.strip()] if entity_types_str else None
enrich = request.args.get('enrich', 'true').lower() == 'true'
@@ -96,7 +96,7 @@ def get_entity_detail(graph_id: str, entity_uuid: str):
if not Config.ZEP_API_KEY:
return jsonify({
"success": False,
- "error": "ZEP_API_KEY未配置"
+ "error": "ZEP_API_KEY not configured"
}), 500
reader = ZepEntityReader()
@@ -105,7 +105,7 @@ def get_entity_detail(graph_id: str, entity_uuid: str):
if not entity:
return jsonify({
"success": False,
- "error": f"实体不存在: {entity_uuid}"
+ "error": f"Entity not found: {entity_uuid}"
}), 404
return jsonify({
@@ -129,7 +129,7 @@ def get_entities_by_type(graph_id: str, entity_type: str):
if not Config.ZEP_API_KEY:
return jsonify({
"success": False,
- "error": "ZEP_API_KEY未配置"
+ "error": "ZEP_API_KEY not configured"
}), 500
enrich = request.args.get('enrich', 'true').lower() == 'true'
@@ -197,21 +197,21 @@ def create_simulation():
if not project_id:
return jsonify({
"success": False,
- "error": "请提供 project_id"
+ "error": "Please provide project_id"
}), 400
project = ProjectManager.get_project(project_id)
if not project:
return jsonify({
"success": False,
- "error": f"项目不存在: {project_id}"
+ "error": f"Project not found: {project_id}"
}), 404
-
+
graph_id = data.get('graph_id') or project.graph_id
if not graph_id:
return jsonify({
"success": False,
- "error": "项目尚未构建图谱,请先调用 /api/graph/build"
+ "error": "Project has no graph built yet, please call /api/graph/build first"
}), 400
manager = SimulationManager()
@@ -259,7 +259,7 @@ def _check_simulation_prepared(simulation_id: str) -> tuple:
# 检查目录是否存在
if not os.path.exists(simulation_dir):
- return False, {"reason": "模拟目录不存在"}
+ return False, {"reason": "Simulation directory not found"}
# 必要文件列表(不包括脚本,脚本位于 backend/scripts/)
required_files = [
@@ -281,7 +281,7 @@ def _check_simulation_prepared(simulation_id: str) -> tuple:
if missing_files:
return False, {
- "reason": "缺少必要文件",
+ "reason": "Missing required files",
"missing_files": missing_files,
"existing_files": existing_files
}
@@ -346,13 +346,13 @@ def _check_simulation_prepared(simulation_id: str) -> tuple:
else:
logger.warning(f"模拟 {simulation_id} 检测结果: 未准备完成 (status={status}, config_generated={config_generated})")
return False, {
- "reason": f"状态不在已准备列表中或config_generated为false: status={status}, config_generated={config_generated}",
+ "reason": f"Status not in prepared list or config_generated is false: status={status}, config_generated={config_generated}",
"status": status,
"config_generated": config_generated
}
except Exception as e:
- return False, {"reason": f"读取状态文件失败: {str(e)}"}
+ return False, {"reason": f"Failed to read state file: {str(e)}"}
@simulation_bp.route('/prepare', methods=['POST'])
@@ -408,18 +408,18 @@ def prepare_simulation():
if not simulation_id:
return jsonify({
"success": False,
- "error": "请提供 simulation_id"
+ "error": "Please provide simulation_id"
}), 400
-
+
manager = SimulationManager()
state = manager.get_simulation(simulation_id)
-
+
if not state:
return jsonify({
"success": False,
- "error": f"模拟不存在: {simulation_id}"
+ "error": f"Simulation not found: {simulation_id}"
}), 404
-
+
# 检查是否强制重新生成
force_regenerate = data.get('force_regenerate', False)
logger.info(f"开始处理 /prepare 请求: simulation_id={simulation_id}, force_regenerate={force_regenerate}")
@@ -436,7 +436,7 @@ def prepare_simulation():
"data": {
"simulation_id": simulation_id,
"status": "ready",
- "message": "已有完成的准备工作,无需重复生成",
+ "message": "Preparation already complete, no need to regenerate",
"already_prepared": True,
"prepare_info": prepare_info
}
@@ -449,15 +449,15 @@ def prepare_simulation():
if not project:
return jsonify({
"success": False,
- "error": f"项目不存在: {state.project_id}"
+ "error": f"Project not found: {state.project_id}"
}), 404
-
+
# 获取模拟需求
simulation_requirement = project.simulation_requirement or ""
if not simulation_requirement:
return jsonify({
"success": False,
- "error": "项目缺少模拟需求描述 (simulation_requirement)"
+ "error": "Project is missing simulation requirement description (simulation_requirement)"
}), 400
# 获取文档文本
@@ -507,7 +507,7 @@ def run_prepare():
task_id,
status=TaskStatus.PROCESSING,
progress=0,
- message="开始准备模拟环境..."
+ message="Starting simulation environment preparation..."
)
# 准备模拟(带进度回调)
@@ -528,10 +528,10 @@ def progress_callback(stage, progress, message, **kwargs):
# 构建详细进度信息
stage_names = {
- "reading": "读取图谱实体",
- "generating_profiles": "生成Agent人设",
- "generating_config": "生成模拟配置",
- "copying_scripts": "准备模拟脚本"
+ "reading": "Reading graph entities",
+ "generating_profiles": "Generating agent personas",
+ "generating_config": "Generating simulation config",
+ "copying_scripts": "Preparing simulation scripts"
}
stage_index = list(stage_weights.keys()).index(stage) + 1 if stage in stage_weights else 1
@@ -612,7 +612,7 @@ def progress_callback(stage, progress, message, **kwargs):
"simulation_id": simulation_id,
"task_id": task_id,
"status": "preparing",
- "message": "准备任务已启动,请通过 /api/simulation/prepare/status 查询进度",
+ "message": "Preparation task started, check progress via /api/simulation/prepare/status",
"already_prepared": False,
"expected_entities_count": state.entities_count, # 预期的Agent总数
"entity_types": state.entity_types # 实体类型列表
@@ -680,7 +680,7 @@ def get_prepare_status():
"simulation_id": simulation_id,
"status": "ready",
"progress": 100,
- "message": "已有完成的准备工作",
+ "message": "Preparation already complete",
"already_prepared": True,
"prepare_info": prepare_info
}
@@ -696,18 +696,18 @@ def get_prepare_status():
"simulation_id": simulation_id,
"status": "not_started",
"progress": 0,
- "message": "尚未开始准备,请调用 /api/simulation/prepare 开始",
+ "message": "Preparation not started, please call /api/simulation/prepare to begin",
"already_prepared": False
}
})
return jsonify({
"success": False,
- "error": "请提供 task_id 或 simulation_id"
+ "error": "Please provide task_id or simulation_id"
}), 400
-
+
task_manager = TaskManager()
task = task_manager.get_task(task_id)
-
+
if not task:
# 任务不存在,但如果有simulation_id,检查是否已准备完成
if simulation_id:
@@ -720,7 +720,7 @@ def get_prepare_status():
"task_id": task_id,
"status": "ready",
"progress": 100,
- "message": "任务已完成(准备工作已存在)",
+ "message": "Task already completed (preparation exists)",
"already_prepared": True,
"prepare_info": prepare_info
}
@@ -728,9 +728,9 @@ def get_prepare_status():
return jsonify({
"success": False,
- "error": f"任务不存在: {task_id}"
+ "error": f"Task not found: {task_id}"
}), 404
-
+
task_dict = task.to_dict()
task_dict["already_prepared"] = False
@@ -757,9 +757,9 @@ def get_simulation(simulation_id: str):
if not state:
return jsonify({
"success": False,
- "error": f"模拟不存在: {simulation_id}"
+ "error": f"Simulation not found: {simulation_id}"
}), 404
-
+
result = state.to_dict()
# 如果模拟已准备好,附加运行说明
@@ -946,7 +946,7 @@ def get_simulation_history():
project = ProjectManager.get_project(sim.project_id)
if project and hasattr(project, 'files') and project.files:
sim_dict["files"] = [
- {"filename": f.get("filename", "未知文件")}
+ {"filename": f.get("filename", "Unknown file")}
for f in project.files[:3]
]
else:
@@ -1061,9 +1061,9 @@ def get_simulation_profiles_realtime(simulation_id: str):
if not os.path.exists(sim_dir):
return jsonify({
"success": False,
- "error": f"模拟不存在: {simulation_id}"
+ "error": f"Simulation not found: {simulation_id}"
}), 404
-
+
# 确定文件路径
if platform == "reddit":
profiles_file = os.path.join(sim_dir, "reddit_profiles.json")
@@ -1164,9 +1164,9 @@ def get_simulation_config_realtime(simulation_id: str):
if not os.path.exists(sim_dir):
return jsonify({
"success": False,
- "error": f"模拟不存在: {simulation_id}"
+ "error": f"Simulation not found: {simulation_id}"
}), 404
-
+
# 配置文件路径
config_file = os.path.join(sim_dir, "simulation_config.json")
@@ -1269,7 +1269,7 @@ def get_simulation_config(simulation_id: str):
if not config:
return jsonify({
"success": False,
- "error": f"模拟配置不存在,请先调用 /prepare 接口"
+ "error": "Simulation config not found, please call /prepare first"
}), 404
return jsonify({
@@ -1297,7 +1297,7 @@ def download_simulation_config(simulation_id: str):
if not os.path.exists(config_path):
return jsonify({
"success": False,
- "error": "配置文件不存在,请先调用 /prepare 接口"
+ "error": "Config file not found, please call /prepare first"
}), 404
return send_file(
@@ -1341,7 +1341,7 @@ def download_simulation_script(script_name: str):
if script_name not in allowed_scripts:
return jsonify({
"success": False,
- "error": f"未知脚本: {script_name},可选: {allowed_scripts}"
+ "error": f"Unknown script: {script_name}, allowed: {allowed_scripts}"
}), 400
script_path = os.path.join(scripts_dir, script_name)
@@ -1349,7 +1349,7 @@ def download_simulation_script(script_name: str):
if not os.path.exists(script_path):
return jsonify({
"success": False,
- "error": f"脚本文件不存在: {script_name}"
+ "error": f"Script file not found: {script_name}"
}), 404
return send_file(
@@ -1389,7 +1389,7 @@ def generate_profiles():
if not graph_id:
return jsonify({
"success": False,
- "error": "请提供 graph_id"
+ "error": "Please provide graph_id"
}), 400
entity_types = data.get('entity_types')
@@ -1406,7 +1406,7 @@ def generate_profiles():
if filtered.filtered_count == 0:
return jsonify({
"success": False,
- "error": "没有找到符合条件的实体"
+ "error": "No matching entities found"
}), 400
generator = OasisProfileGenerator()
@@ -1491,7 +1491,7 @@ def start_simulation():
if not simulation_id:
return jsonify({
"success": False,
- "error": "请提供 simulation_id"
+ "error": "Please provide simulation_id"
}), 400
platform = data.get('platform', 'parallel')
@@ -1506,18 +1506,18 @@ def start_simulation():
if max_rounds <= 0:
return jsonify({
"success": False,
- "error": "max_rounds 必须是正整数"
+ "error": "max_rounds must be a positive integer"
}), 400
except (ValueError, TypeError):
return jsonify({
"success": False,
- "error": "max_rounds 必须是有效的整数"
+ "error": "max_rounds must be a valid integer"
}), 400
if platform not in ['twitter', 'reddit', 'parallel']:
return jsonify({
"success": False,
- "error": f"无效的平台类型: {platform},可选: twitter/reddit/parallel"
+ "error": f"Invalid platform type: {platform}, allowed: twitter/reddit/parallel"
}), 400
# 检查模拟是否已准备好
@@ -1527,7 +1527,7 @@ def start_simulation():
if not state:
return jsonify({
"success": False,
- "error": f"模拟不存在: {simulation_id}"
+ "error": f"Simulation not found: {simulation_id}"
}), 404
force_restarted = False
@@ -1554,7 +1554,7 @@ def start_simulation():
else:
return jsonify({
"success": False,
- "error": f"模拟正在运行中,请先调用 /stop 接口停止,或使用 force=true 强制重新开始"
+ "error": "Simulation is currently running, please call /stop first or use force=true to force restart"
}), 400
# 如果是强制模式,清理运行日志
@@ -1573,7 +1573,7 @@ def start_simulation():
# 准备工作未完成
return jsonify({
"success": False,
- "error": f"模拟未准备好,当前状态: {state.status.value},请先调用 /prepare 接口"
+ "error": f"Simulation not ready, current status: {state.status.value}, please call /prepare first"
}), 400
# 获取图谱ID(用于图谱记忆更新)
@@ -1590,7 +1590,7 @@ def start_simulation():
if not graph_id:
return jsonify({
"success": False,
- "error": "启用图谱记忆更新需要有效的 graph_id,请确保项目已构建图谱"
+ "error": "Graph memory update requires a valid graph_id, please ensure the project graph has been built"
}), 400
logger.info(f"启用图谱记忆更新: simulation_id={simulation_id}, graph_id={graph_id}")
@@ -1663,9 +1663,9 @@ def stop_simulation():
if not simulation_id:
return jsonify({
"success": False,
- "error": "请提供 simulation_id"
+ "error": "Please provide simulation_id"
}), 400
-
+
run_state = SimulationRunner.stop_simulation(simulation_id)
# 更新模拟状态
@@ -2011,7 +2011,7 @@ def get_simulation_posts(simulation_id: str):
"platform": platform,
"count": 0,
"posts": [],
- "message": "数据库不存在,模拟可能尚未运行"
+ "message": "Database does not exist, simulation may not have run yet"
}
})
@@ -2197,38 +2197,38 @@ def interview_agent():
if not simulation_id:
return jsonify({
"success": False,
- "error": "请提供 simulation_id"
+ "error": "Please provide simulation_id"
}), 400
-
+
if agent_id is None:
return jsonify({
"success": False,
- "error": "请提供 agent_id"
+ "error": "Please provide agent_id"
}), 400
if not prompt:
return jsonify({
"success": False,
- "error": "请提供 prompt(采访问题)"
+ "error": "Please provide prompt (interview question)"
}), 400
-
+
# 验证platform参数
if platform and platform not in ("twitter", "reddit"):
return jsonify({
"success": False,
- "error": "platform 参数只能是 'twitter' 或 'reddit'"
+ "error": "platform must be 'twitter' or 'reddit'"
}), 400
-
+
# 检查环境状态
if not SimulationRunner.check_env_alive(simulation_id):
return jsonify({
"success": False,
- "error": "模拟环境未运行或已关闭。请确保模拟已完成并进入等待命令模式。"
+ "error": "Simulation environment is not running or has been closed. Please ensure the simulation has completed and is in command-waiting mode."
}), 400
-
+
# 优化prompt,添加前缀避免Agent调用工具
optimized_prompt = optimize_interview_prompt(prompt)
-
+
result = SimulationRunner.interview_agent(
simulation_id=simulation_id,
agent_id=agent_id,
@@ -2251,7 +2251,7 @@ def interview_agent():
except TimeoutError as e:
return jsonify({
"success": False,
- "error": f"等待Interview响应超时: {str(e)}"
+ "error": f"Interview response timed out: {str(e)}"
}), 504
except Exception as e:
@@ -2318,20 +2318,20 @@ def interview_agents_batch():
if not simulation_id:
return jsonify({
"success": False,
- "error": "请提供 simulation_id"
+ "error": "Please provide simulation_id"
}), 400
if not interviews or not isinstance(interviews, list):
return jsonify({
"success": False,
- "error": "请提供 interviews(采访列表)"
+ "error": "Please provide interviews (interview list)"
}), 400
# 验证platform参数
if platform and platform not in ("twitter", "reddit"):
return jsonify({
"success": False,
- "error": "platform 参数只能是 'twitter' 或 'reddit'"
+ "error": "platform must be 'twitter' or 'reddit'"
}), 400
# 验证每个采访项
@@ -2339,26 +2339,26 @@ def interview_agents_batch():
if 'agent_id' not in interview:
return jsonify({
"success": False,
- "error": f"采访列表第{i+1}项缺少 agent_id"
+ "error": f"Interview item {i+1} is missing agent_id"
}), 400
if 'prompt' not in interview:
return jsonify({
"success": False,
- "error": f"采访列表第{i+1}项缺少 prompt"
+ "error": f"Interview item {i+1} is missing prompt"
}), 400
# 验证每项的platform(如果有)
item_platform = interview.get('platform')
if item_platform and item_platform not in ("twitter", "reddit"):
return jsonify({
"success": False,
- "error": f"采访列表第{i+1}项的platform只能是 'twitter' 或 'reddit'"
+ "error": f"Interview item {i+1} platform must be 'twitter' or 'reddit'"
}), 400
# 检查环境状态
if not SimulationRunner.check_env_alive(simulation_id):
return jsonify({
"success": False,
- "error": "模拟环境未运行或已关闭。请确保模拟已完成并进入等待命令模式。"
+ "error": "Simulation environment is not running or has been closed. Please ensure the simulation has completed and is in command-waiting mode."
}), 400
# 优化每个采访项的prompt,添加前缀避免Agent调用工具
@@ -2389,7 +2389,7 @@ def interview_agents_batch():
except TimeoutError as e:
return jsonify({
"success": False,
- "error": f"等待批量Interview响应超时: {str(e)}"
+ "error": f"Batch interview response timed out: {str(e)}"
}), 504
except Exception as e:
@@ -2445,27 +2445,27 @@ def interview_all_agents():
if not simulation_id:
return jsonify({
"success": False,
- "error": "请提供 simulation_id"
+ "error": "Please provide simulation_id"
}), 400
if not prompt:
return jsonify({
"success": False,
- "error": "请提供 prompt(采访问题)"
+ "error": "Please provide prompt (interview question)"
}), 400
# 验证platform参数
if platform and platform not in ("twitter", "reddit"):
return jsonify({
"success": False,
- "error": "platform 参数只能是 'twitter' 或 'reddit'"
+ "error": "platform must be 'twitter' or 'reddit'"
}), 400
# 检查环境状态
if not SimulationRunner.check_env_alive(simulation_id):
return jsonify({
"success": False,
- "error": "模拟环境未运行或已关闭。请确保模拟已完成并进入等待命令模式。"
+ "error": "Simulation environment is not running or has been closed. Please ensure the simulation has completed and is in command-waiting mode."
}), 400
# 优化prompt,添加前缀避免Agent调用工具
@@ -2492,7 +2492,7 @@ def interview_all_agents():
except TimeoutError as e:
return jsonify({
"success": False,
- "error": f"等待全局Interview响应超时: {str(e)}"
+ "error": f"Global interview response timed out: {str(e)}"
}), 504
except Exception as e:
@@ -2549,7 +2549,7 @@ def get_interview_history():
if not simulation_id:
return jsonify({
"success": False,
- "error": "请提供 simulation_id"
+ "error": "Please provide simulation_id"
}), 400
history = SimulationRunner.get_interview_history(
@@ -2608,7 +2608,7 @@ def get_env_status():
if not simulation_id:
return jsonify({
"success": False,
- "error": "请提供 simulation_id"
+ "error": "Please provide simulation_id"
}), 400
env_alive = SimulationRunner.check_env_alive(simulation_id)
@@ -2617,9 +2617,9 @@ def get_env_status():
env_status = SimulationRunner.get_env_status_detail(simulation_id)
if env_alive:
- message = "环境正在运行,可以接收Interview命令"
+ message = "Environment is running and can receive interview commands"
else:
- message = "环境未运行或已关闭"
+ message = "Environment is not running or has been closed"
return jsonify({
"success": True,
@@ -2676,9 +2676,9 @@ def close_simulation_env():
if not simulation_id:
return jsonify({
"success": False,
- "error": "请提供 simulation_id"
+ "error": "Please provide simulation_id"
}), 400
-
+
result = SimulationRunner.close_simulation_env(
simulation_id=simulation_id,
timeout=timeout
diff --git a/backend/app/models/task.py b/backend/app/models/task.py
index e15f35fbd..9f2c64903 100644
--- a/backend/app/models/task.py
+++ b/backend/app/models/task.py
@@ -148,7 +148,7 @@ def complete_task(self, task_id: str, result: Dict):
task_id,
status=TaskStatus.COMPLETED,
progress=100,
- message="任务完成",
+ message="Task completed",
result=result
)
@@ -157,7 +157,7 @@ def fail_task(self, task_id: str, error: str):
self.update_task(
task_id,
status=TaskStatus.FAILED,
- message="任务失败",
+ message="Task failed",
error=error
)
diff --git a/backend/app/services/graph_builder.py b/backend/app/services/graph_builder.py
index 0e0444bf3..eef3045a9 100644
--- a/backend/app/services/graph_builder.py
+++ b/backend/app/services/graph_builder.py
@@ -45,7 +45,7 @@ class GraphBuilderService:
def __init__(self, api_key: Optional[str] = None):
self.api_key = api_key or Config.ZEP_API_KEY
if not self.api_key:
- raise ValueError("ZEP_API_KEY 未配置")
+ raise ValueError("ZEP_API_KEY not configured")
self.client = Zep(api_key=self.api_key)
self.task_manager = TaskManager()
@@ -109,7 +109,7 @@ def _build_graph_worker(
task_id,
status=TaskStatus.PROCESSING,
progress=5,
- message="开始构建图谱..."
+ message="Starting graph build..."
)
# 1. 创建图谱
@@ -117,7 +117,7 @@ def _build_graph_worker(
self.task_manager.update_task(
task_id,
progress=10,
- message=f"图谱已创建: {graph_id}"
+ message=f"Graph created: {graph_id}"
)
# 2. 设置本体
@@ -125,7 +125,7 @@ def _build_graph_worker(
self.task_manager.update_task(
task_id,
progress=15,
- message="本体已设置"
+ message="Ontology set"
)
# 3. 文本分块
@@ -134,7 +134,7 @@ def _build_graph_worker(
self.task_manager.update_task(
task_id,
progress=20,
- message=f"文本已分割为 {total_chunks} 个块"
+ message=f"Text split into {total_chunks} chunks"
)
# 4. 分批发送数据
@@ -151,7 +151,7 @@ def _build_graph_worker(
self.task_manager.update_task(
task_id,
progress=60,
- message="等待Zep处理数据..."
+ message="Waiting for Zep to process data..."
)
self._wait_for_episodes(
@@ -167,7 +167,7 @@ def _build_graph_worker(
self.task_manager.update_task(
task_id,
progress=90,
- message="获取图谱信息..."
+ message="Retrieving graph info..."
)
graph_info = self._get_graph_info(graph_id)
@@ -304,7 +304,7 @@ def add_text_batches(
if progress_callback:
progress = (i + len(batch_chunks)) / total_chunks
progress_callback(
- f"发送第 {batch_num}/{total_batches} 批数据 ({len(batch_chunks)} 块)...",
+ f"Sending batch {batch_num}/{total_batches} ({len(batch_chunks)} chunks)...",
progress
)
@@ -333,7 +333,7 @@ def add_text_batches(
except Exception as e:
if progress_callback:
- progress_callback(f"批次 {batch_num} 发送失败: {str(e)}", 0)
+ progress_callback(f"Batch {batch_num} send failed: {str(e)}", 0)
raise
return episode_uuids
@@ -347,7 +347,7 @@ def _wait_for_episodes(
"""等待所有 episode 处理完成(通过查询每个 episode 的 processed 状态)"""
if not episode_uuids:
if progress_callback:
- progress_callback("无需等待(没有 episode)", 1.0)
+ progress_callback("No waiting needed (no episodes)", 1.0)
return
start_time = time.time()
@@ -356,13 +356,13 @@ def _wait_for_episodes(
total_episodes = len(episode_uuids)
if progress_callback:
- progress_callback(f"开始等待 {total_episodes} 个文本块处理...", 0)
+ progress_callback(f"Waiting for {total_episodes} text chunks to process...", 0)
while pending_episodes:
if time.time() - start_time > timeout:
if progress_callback:
progress_callback(
- f"部分文本块超时,已完成 {completed_count}/{total_episodes}",
+ f"Some text chunks timed out, completed {completed_count}/{total_episodes}",
completed_count / total_episodes
)
break
@@ -384,7 +384,7 @@ def _wait_for_episodes(
elapsed = int(time.time() - start_time)
if progress_callback:
progress_callback(
- f"Zep处理中... {completed_count}/{total_episodes} 完成, {len(pending_episodes)} 待处理 ({elapsed}秒)",
+ f"Zep processing... {completed_count}/{total_episodes} done, {len(pending_episodes)} pending ({elapsed}s)",
completed_count / total_episodes if total_episodes > 0 else 0
)
@@ -392,7 +392,7 @@ def _wait_for_episodes(
time.sleep(3) # 每3秒检查一次
if progress_callback:
- progress_callback(f"处理完成: {completed_count}/{total_episodes}", 1.0)
+ progress_callback(f"Processing complete: {completed_count}/{total_episodes}", 1.0)
def _get_graph_info(self, graph_id: str) -> GraphInfo:
"""获取图谱信息"""
diff --git a/backend/app/services/report_agent.py b/backend/app/services/report_agent.py
index 02ca5bdc2..a3abe3ffe 100644
--- a/backend/app/services/report_agent.py
+++ b/backend/app/services/report_agent.py
@@ -105,7 +105,7 @@ def log_start(self, simulation_id: str, graph_id: str, simulation_requirement: s
"simulation_id": simulation_id,
"graph_id": graph_id,
"simulation_requirement": simulation_requirement,
- "message": "报告生成任务开始"
+ "message": "Report generation task started"
}
)
@@ -114,7 +114,7 @@ def log_planning_start(self):
self.log(
action="planning_start",
stage="planning",
- details={"message": "开始规划报告大纲"}
+ details={"message": "Starting report outline planning"}
)
def log_planning_context(self, context: Dict[str, Any]):
@@ -123,7 +123,7 @@ def log_planning_context(self, context: Dict[str, Any]):
action="planning_context",
stage="planning",
details={
- "message": "获取模拟上下文信息",
+ "message": "Retrieving simulation context",
"context": context
}
)
@@ -134,7 +134,7 @@ def log_planning_complete(self, outline_dict: Dict[str, Any]):
action="planning_complete",
stage="planning",
details={
- "message": "大纲规划完成",
+ "message": "Outline planning complete",
"outline": outline_dict
}
)
@@ -146,7 +146,7 @@ def log_section_start(self, section_title: str, section_index: int):
stage="generating",
section_title=section_title,
section_index=section_index,
- details={"message": f"开始生成章节: {section_title}"}
+ details={"message": f"Starting section generation: {section_title}"}
)
def log_react_thought(self, section_title: str, section_index: int, iteration: int, thought: str):
@@ -159,7 +159,7 @@ def log_react_thought(self, section_title: str, section_index: int, iteration: i
details={
"iteration": iteration,
"thought": thought,
- "message": f"ReACT 第{iteration}轮思考"
+ "message": f"ReACT iteration {iteration} thinking"
}
)
@@ -181,7 +181,7 @@ def log_tool_call(
"iteration": iteration,
"tool_name": tool_name,
"parameters": parameters,
- "message": f"调用工具: {tool_name}"
+ "message": f"Calling tool: {tool_name}"
}
)
@@ -204,7 +204,7 @@ def log_tool_result(
"tool_name": tool_name,
"result": result, # 完整结果,不截断
"result_length": len(result),
- "message": f"工具 {tool_name} 返回结果"
+ "message": f"Tool {tool_name} returned result"
}
)
@@ -229,7 +229,7 @@ def log_llm_response(
"response_length": len(response),
"has_tool_calls": has_tool_calls,
"has_final_answer": has_final_answer,
- "message": f"LLM 响应 (工具调用: {has_tool_calls}, 最终答案: {has_final_answer})"
+ "message": f"LLM response (tool calls: {has_tool_calls}, final answer: {has_final_answer})"
}
)
@@ -250,7 +250,7 @@ def log_section_content(
"content": content, # 完整内容,不截断
"content_length": len(content),
"tool_calls_count": tool_calls_count,
- "message": f"章节 {section_title} 内容生成完成"
+ "message": f"Section {section_title} content generation complete"
}
)
@@ -273,7 +273,7 @@ def log_section_full_complete(
details={
"content": full_content,
"content_length": len(full_content),
- "message": f"章节 {section_title} 生成完成"
+ "message": f"Section {section_title} generation complete"
}
)
@@ -285,7 +285,7 @@ def log_report_complete(self, total_sections: int, total_time_seconds: float):
details={
"total_sections": total_sections,
"total_time_seconds": round(total_time_seconds, 2),
- "message": "报告生成完成"
+ "message": "Report generation complete"
}
)
@@ -298,7 +298,7 @@ def log_error(self, error_message: str, stage: str, section_title: str = None):
section_index=None,
details={
"error": error_message,
- "message": f"发生错误: {error_message}"
+ "message": f"Error occurred: {error_message}"
}
)
@@ -467,393 +467,394 @@ def to_dict(self) -> Dict[str, Any]:
# ═══════════════════════════════════════════════════════════════
-# Prompt 模板常量
+# Prompt Template Constants
# ═══════════════════════════════════════════════════════════════
-# ── 工具描述 ──
+# ── Tool Descriptions ──
TOOL_DESC_INSIGHT_FORGE = """\
-【深度洞察检索 - 强大的检索工具】
-这是我们强大的检索函数,专为深度分析设计。它会:
-1. 自动将你的问题分解为多个子问题
-2. 从多个维度检索模拟图谱中的信息
-3. 整合语义搜索、实体分析、关系链追踪的结果
-4. 返回最全面、最深度的检索内容
-
-【使用场景】
-- 需要深入分析某个话题
-- 需要了解事件的多个方面
-- 需要获取支撑报告章节的丰富素材
-
-【返回内容】
-- 相关事实原文(可直接引用)
-- 核心实体洞察
-- 关系链分析"""
+[Deep Insight Retrieval - Powerful Retrieval Tool]
+This is our powerful retrieval function, designed for in-depth analysis. It will:
+1. Automatically decompose your question into multiple sub-questions
+2. Retrieve information from the simulation graph across multiple dimensions
+3. Integrate results from semantic search, entity analysis, and relationship chain tracking
+4. Return the most comprehensive and in-depth retrieval content
+
+[Use Cases]
+- Need to deeply analyze a topic
+- Need to understand multiple aspects of an event
+- Need to obtain rich material to support report sections
+
+[Return Content]
+- Relevant original facts (can be directly quoted)
+- Core entity insights
+- Relationship chain analysis"""
TOOL_DESC_PANORAMA_SEARCH = """\
-【广度搜索 - 获取全貌视图】
-这个工具用于获取模拟结果的完整全貌,特别适合了解事件演变过程。它会:
-1. 获取所有相关节点和关系
-2. 区分当前有效的事实和历史/过期的事实
-3. 帮助你了解舆情是如何演变的
-
-【使用场景】
-- 需要了解事件的完整发展脉络
-- 需要对比不同阶段的舆情变化
-- 需要获取全面的实体和关系信息
-
-【返回内容】
-- 当前有效事实(模拟最新结果)
-- 历史/过期事实(演变记录)
-- 所有涉及的实体"""
+[Broad Search - Get a Panoramic View]
+This tool is used to get a complete overview of simulation results, especially suitable for understanding event evolution. It will:
+1. Retrieve all related nodes and relationships
+2. Distinguish between currently valid facts and historical/expired facts
+3. Help you understand how public sentiment evolved
+
+[Use Cases]
+- Need to understand the complete development trajectory of an event
+- Need to compare sentiment changes across different stages
+- Need to obtain comprehensive entity and relationship information
+
+[Return Content]
+- Currently valid facts (latest simulation results)
+- Historical/expired facts (evolution records)
+- All involved entities"""
TOOL_DESC_QUICK_SEARCH = """\
-【简单搜索 - 快速检索】
-轻量级的快速检索工具,适合简单、直接的信息查询。
+[Simple Search - Quick Retrieval]
+A lightweight quick retrieval tool, suitable for simple and direct information queries.
-【使用场景】
-- 需要快速查找某个具体信息
-- 需要验证某个事实
-- 简单的信息检索
+[Use Cases]
+- Need to quickly look up a specific piece of information
+- Need to verify a fact
+- Simple information retrieval
-【返回内容】
-- 与查询最相关的事实列表"""
+[Return Content]
+- A list of facts most relevant to the query"""
TOOL_DESC_INTERVIEW_AGENTS = """\
-【深度采访 - 真实Agent采访(双平台)】
-调用OASIS模拟环境的采访API,对正在运行的模拟Agent进行真实采访!
-这不是LLM模拟,而是调用真实的采访接口获取模拟Agent的原始回答。
-默认在Twitter和Reddit两个平台同时采访,获取更全面的观点。
-
-功能流程:
-1. 自动读取人设文件,了解所有模拟Agent
-2. 智能选择与采访主题最相关的Agent(如学生、媒体、官方等)
-3. 自动生成采访问题
-4. 调用 /api/simulation/interview/batch 接口在双平台进行真实采访
-5. 整合所有采访结果,提供多视角分析
-
-【使用场景】
-- 需要从不同角色视角了解事件看法(学生怎么看?媒体怎么看?官方怎么说?)
-- 需要收集多方意见和立场
-- 需要获取模拟Agent的真实回答(来自OASIS模拟环境)
-- 想让报告更生动,包含"采访实录"
-
-【返回内容】
-- 被采访Agent的身份信息
-- 各Agent在Twitter和Reddit两个平台的采访回答
-- 关键引言(可直接引用)
-- 采访摘要和观点对比
-
-【重要】需要OASIS模拟环境正在运行才能使用此功能!"""
-
-# ── 大纲规划 prompt ──
+[In-Depth Interview - Real Agent Interview (Dual Platform)]
+Calls the OASIS simulation environment interview API to conduct real interviews with running simulation Agents!
+This is not an LLM simulation, but calls the real interview interface to get original responses from simulation Agents.
+By default, interviews are conducted simultaneously on both Twitter and Reddit platforms for more comprehensive perspectives.
+
+Workflow:
+1. Automatically reads persona files to learn about all simulation Agents
+2. Intelligently selects Agents most relevant to the interview topic (e.g., students, media, officials, etc.)
+3. Automatically generates interview questions
+4. Calls the /api/simulation/interview/batch endpoint to conduct real interviews on both platforms
+5. Integrates all interview results to provide multi-perspective analysis
+
+[Use Cases]
+- Need to understand event perspectives from different roles (What do students think? What does the media think? What do officials say?)
+- Need to collect opinions and positions from multiple parties
+- Need to obtain real responses from simulation Agents (from the OASIS simulation environment)
+- Want to make the report more vivid by including "interview transcripts"
+
+[Return Content]
+- Identity information of interviewed Agents
+- Interview responses from each Agent on both Twitter and Reddit platforms
+- Key quotes (can be directly cited)
+- Interview summary and comparison of viewpoints
+
+[Important] The OASIS simulation environment must be running to use this feature!"""
+
+# ── Outline Planning Prompt ──
PLAN_SYSTEM_PROMPT = """\
-你是一个「未来预测报告」的撰写专家,拥有对模拟世界的「上帝视角」——你可以洞察模拟中每一位Agent的行为、言论和互动。
-
-【核心理念】
-我们构建了一个模拟世界,并向其中注入了特定的「模拟需求」作为变量。模拟世界的演化结果,就是对未来可能发生情况的预测。你正在观察的不是"实验数据",而是"未来的预演"。
-
-【你的任务】
-撰写一份「未来预测报告」,回答:
-1. 在我们设定的条件下,未来发生了什么?
-2. 各类Agent(人群)是如何反应和行动?
-3. 这个模拟揭示了哪些值得关注的未来趋势和风险?
-
-【报告定位】
-- ✅ 这是一份基于模拟的未来预测报告,揭示"如果这样,未来会怎样"
-- ✅ 聚焦于预测结果:事件走向、群体反应、涌现现象、潜在风险
-- ✅ 模拟世界中的Agent言行就是对未来人群行为的预测
-- ❌ 不是对现实世界现状的分析
-- ❌ 不是泛泛而谈的舆情综述
-
-【章节数量限制】
-- 最少2个章节,最多5个章节
-- 不需要子章节,每个章节直接撰写完整内容
-- 内容要精炼,聚焦于核心预测发现
-- 章节结构由你根据预测结果自主设计
-
-请输出JSON格式的报告大纲,格式如下:
+You are an expert in writing "Future Prediction Reports," possessing a "God's-eye view" of the simulated world -- you can observe the behavior, statements, and interactions of every Agent in the simulation.
+
+[Core Concept]
+We have built a simulated world and injected specific "simulation requirements" as variables. The evolution results of the simulated world represent predictions of what may happen in the future. What you are observing is not "experimental data," but a "rehearsal of the future."
+
+[Your Task]
+Write a "Future Prediction Report" that answers:
+1. Under the conditions we set, what happened in the future?
+2. How did various types of Agents (populations) react and act?
+3. What noteworthy future trends and risks does this simulation reveal?
+
+[Report Positioning]
+- This is a simulation-based future prediction report, revealing "if this happens, what will the future look like"
+- Focus on prediction results: event trajectories, group reactions, emergent phenomena, potential risks
+- The statements and actions of Agents in the simulated world are predictions of future human behavior
+- This is NOT an analysis of real-world current conditions
+- This is NOT a generic public sentiment overview
+
+[Section Count Limits]
+- Minimum 2 sections, maximum 5 sections
+- No sub-sections needed; each section should contain complete content directly
+- Content should be concise, focusing on core prediction findings
+- Section structure should be designed by you based on the prediction results
+
+Please output the report outline in JSON format as follows:
{
- "title": "报告标题",
- "summary": "报告摘要(一句话概括核心预测发现)",
+ "title": "Report title",
+ "summary": "Report summary (one sentence summarizing core prediction findings)",
"sections": [
{
- "title": "章节标题",
- "description": "章节内容描述"
+ "title": "Section title",
+ "description": "Section content description"
}
]
}
-注意:sections数组最少2个,最多5个元素!"""
+Note: The sections array must have at least 2 and at most 5 elements!"""
PLAN_USER_PROMPT_TEMPLATE = """\
-【预测场景设定】
-我们向模拟世界注入的变量(模拟需求):{simulation_requirement}
+[Prediction Scenario Setup]
+Variables injected into the simulated world (simulation requirements): {simulation_requirement}
-【模拟世界规模】
-- 参与模拟的实体数量: {total_nodes}
-- 实体间产生的关系数量: {total_edges}
-- 实体类型分布: {entity_types}
-- 活跃Agent数量: {total_entities}
+[Simulated World Scale]
+- Number of entities participating in the simulation: {total_nodes}
+- Number of relationships generated between entities: {total_edges}
+- Entity type distribution: {entity_types}
+- Number of active Agents: {total_entities}
-【模拟预测到的部分未来事实样本】
+[Sample Future Facts Predicted by the Simulation]
{related_facts_json}
-请以「上帝视角」审视这个未来预演:
-1. 在我们设定的条件下,未来呈现出了什么样的状态?
-2. 各类人群(Agent)是如何反应和行动的?
-3. 这个模拟揭示了哪些值得关注的未来趋势?
+Examine this future rehearsal from a "God's-eye view":
+1. Under the conditions we set, what state does the future present?
+2. How did various populations (Agents) react and act?
+3. What noteworthy future trends does this simulation reveal?
-根据预测结果,设计最合适的报告章节结构。
+Based on the prediction results, design the most appropriate report section structure.
-【再次提醒】报告章节数量:最少2个,最多5个,内容要精炼聚焦于核心预测发现。"""
+[Reminder] Report section count: minimum 2, maximum 5, content should be concise and focused on core prediction findings."""
-# ── 章节生成 prompt ──
+# ── Section Generation Prompt ──
SECTION_SYSTEM_PROMPT_TEMPLATE = """\
-你是一个「未来预测报告」的撰写专家,正在撰写报告的一个章节。
+You are an expert in writing "Future Prediction Reports," currently writing one section of the report.
-报告标题: {report_title}
-报告摘要: {report_summary}
-预测场景(模拟需求): {simulation_requirement}
+Report title: {report_title}
+Report summary: {report_summary}
+Prediction scenario (simulation requirements): {simulation_requirement}
-当前要撰写的章节: {section_title}
+Section to write: {section_title}
═══════════════════════════════════════════════════════════════
-【核心理念】
+[Core Concept]
═══════════════════════════════════════════════════════════════
-模拟世界是对未来的预演。我们向模拟世界注入了特定条件(模拟需求),
-模拟中Agent的行为和互动,就是对未来人群行为的预测。
+The simulated world is a rehearsal of the future. We injected specific conditions (simulation requirements) into the simulated world. The behavior and interactions of Agents in the simulation are predictions of future human behavior.
-你的任务是:
-- 揭示在设定条件下,未来发生了什么
-- 预测各类人群(Agent)是如何反应和行动的
-- 发现值得关注的未来趋势、风险和机会
+Your task is to:
+- Reveal what happened in the future under the set conditions
+- Predict how various populations (Agents) reacted and acted
+- Discover noteworthy future trends, risks, and opportunities
-❌ 不要写成对现实世界现状的分析
-✅ 要聚焦于"未来会怎样"——模拟结果就是预测的未来
+Do NOT write this as an analysis of real-world current conditions.
+DO focus on "what will the future look like" -- the simulation results ARE the predicted future.
═══════════════════════════════════════════════════════════════
-【最重要的规则 - 必须遵守】
+[Most Important Rules - Must Follow]
═══════════════════════════════════════════════════════════════
-1. 【必须调用工具观察模拟世界】
- - 你正在以「上帝视角」观察未来的预演
- - 所有内容必须来自模拟世界中发生的事件和Agent言行
- - 禁止使用你自己的知识来编写报告内容
- - 每个章节至少调用3次工具(最多5次)来观察模拟的世界,它代表了未来
-
-2. 【必须引用Agent的原始言行】
- - Agent的发言和行为是对未来人群行为的预测
- - 在报告中使用引用格式展示这些预测,例如:
- > "某类人群会表示:原文内容..."
- - 这些引用是模拟预测的核心证据
-
-3. 【语言一致性 - 引用内容必须翻译为报告语言】
- - 工具返回的内容可能包含英文或中英文混杂的表述
- - 如果模拟需求和材料原文是中文的,报告必须全部使用中文撰写
- - 当你引用工具返回的英文或中英混杂内容时,必须将其翻译为流畅的中文后再写入报告
- - 翻译时保持原意不变,确保表述自然通顺
- - 这一规则同时适用于正文和引用块(> 格式)中的内容
-
-4. 【忠实呈现预测结果】
- - 报告内容必须反映模拟世界中的代表未来的模拟结果
- - 不要添加模拟中不存在的信息
- - 如果某方面信息不足,如实说明
+1. [Must Call Tools to Observe the Simulated World]
+ - You are observing the future rehearsal from a "God's-eye view"
+ - All content must come from events and Agent statements/actions in the simulated world
+ - Do not use your own knowledge to write report content
+ - Each section must call tools at least 3 times (maximum 5) to observe the simulated world, which represents the future
+
+2. [Must Quote Agents' Original Statements and Actions]
+ - Agent statements and behaviors are predictions of future human behavior
+ - Use quote formatting in the report to present these predictions, for example:
+ > "A certain group would say: original content..."
+ - These quotes are the core evidence of the simulation predictions
+
+3. [CRITICAL - ALL Content Must Be in English, NO EXCEPTIONS]
+ - The ENTIRE report MUST be written in English, including ALL quotes and blockquotes.
+ - Tool results and agent responses may contain Chinese text. You MUST translate ALL Chinese text into fluent English before including it in the report.
+ - NEVER include any Chinese characters in the report output. Every single quote, blockquote (> format), and body text must be in English.
+ - When translating quotes, preserve the original meaning but write them in natural English.
+ - This is a hard requirement: if you encounter Chinese text from tools, translate it first, then include the English translation.
+
+4. [Faithfully Present Prediction Results]
+ - Report content must reflect the simulation results representing the future in the simulated world
+ - Do not add information that does not exist in the simulation
+ - If information is insufficient in certain areas, state this honestly
═══════════════════════════════════════════════════════════════
-【⚠️ 格式规范 - 极其重要!】
+[Format Guidelines - Extremely Important!]
═══════════════════════════════════════════════════════════════
-【一个章节 = 最小内容单位】
-- 每个章节是报告的最小分块单位
-- ❌ 禁止在章节内使用任何 Markdown 标题(#、##、###、#### 等)
-- ❌ 禁止在内容开头添加章节主标题
-- ✅ 章节标题由系统自动添加,你只需撰写纯正文内容
-- ✅ 使用**粗体**、段落分隔、引用、列表来组织内容,但不要用标题
+[One Section = Minimum Content Unit]
+- Each section is the smallest divisible unit of the report
+- Do NOT use any Markdown headings (#, ##, ###, ####, etc.) within a section
+- Do NOT add the section title at the beginning of the content
+- The section title is automatically added by the system; you only need to write body text
+- USE **bold text**, paragraph breaks, quotes, and lists to organize content, but do not use headings
-【正确示例】
+[Correct Example]
```
-本章节分析了事件的舆论传播态势。通过对模拟数据的深入分析,我们发现...
+This section analyzes the public opinion propagation dynamics of the event. Through in-depth analysis of simulation data, we found...
-**首发引爆阶段**
+**Initial Breakout Phase**
-微博作为舆情的第一现场,承担了信息首发的核心功能:
+Weibo, as the frontline of public sentiment, served the core function of information dissemination:
-> "微博贡献了68%的首发声量..."
+> "Weibo contributed 68% of the initial volume..."
-**情绪放大阶段**
+**Sentiment Amplification Phase**
-抖音平台进一步放大了事件影响力:
+The Douyin platform further amplified the event's impact:
-- 视觉冲击力强
-- 情绪共鸣度高
+- Strong visual impact
+- High emotional resonance
```
-【错误示例】
+[Incorrect Example]
```
-## 执行摘要 ← 错误!不要添加任何标题
-### 一、首发阶段 ← 错误!不要用###分小节
-#### 1.1 详细分析 ← 错误!不要用####细分
+## Executive Summary <-- Wrong! Do not add any headings
+### 1. Initial Phase <-- Wrong! Do not use ### for subsections
+#### 1.1 Detailed Analysis <-- Wrong! Do not use #### for further subdivision
-本章节分析了...
+This section analyzes...
```
═══════════════════════════════════════════════════════════════
-【可用检索工具】(每章节调用3-5次)
+[Available Retrieval Tools] (call 3-5 times per section)
═══════════════════════════════════════════════════════════════
{tools_description}
-【工具使用建议 - 请混合使用不同工具,不要只用一种】
-- insight_forge: 深度洞察分析,自动分解问题并多维度检索事实和关系
-- panorama_search: 广角全景搜索,了解事件全貌、时间线和演变过程
-- quick_search: 快速验证某个具体信息点
-- interview_agents: 采访模拟Agent,获取不同角色的第一人称观点和真实反应
+[Tool Usage Suggestions - Please mix different tools, do not use only one]
+- insight_forge: Deep insight analysis, automatically decomposes questions and retrieves facts and relationships across multiple dimensions
+- panorama_search: Wide-angle panoramic search, understand the full picture of events, timelines, and evolution
+- quick_search: Quickly verify a specific piece of information
+- interview_agents: Interview simulation Agents, obtain first-person perspectives and real reactions from different roles
═══════════════════════════════════════════════════════════════
-【工作流程】
+[Workflow]
═══════════════════════════════════════════════════════════════
-每次回复你只能做以下两件事之一(不可同时做):
+Each response can only do one of the following two things (not both):
-选项A - 调用工具:
-输出你的思考,然后用以下格式调用一个工具:
+Option A - Call a tool:
+Output your thinking, then call a tool using the following format:
-{{"name": "工具名称", "parameters": {{"参数名": "参数值"}}}}
+{{"name": "tool_name", "parameters": {{"param_name": "param_value"}}}}
-系统会执行工具并把结果返回给你。你不需要也不能自己编写工具返回结果。
+The system will execute the tool and return the results to you. You do not need to and cannot write tool return results yourself.
-选项B - 输出最终内容:
-当你已通过工具获取了足够信息,以 "Final Answer:" 开头输出章节内容。
+Option B - Output final content:
+When you have obtained enough information through tools, output the section content starting with "Final Answer:".
-⚠️ 严格禁止:
-- 禁止在一次回复中同时包含工具调用和 Final Answer
-- 禁止自己编造工具返回结果(Observation),所有工具结果由系统注入
-- 每次回复最多调用一个工具
+Strictly prohibited:
+- Do not include both a tool call and a Final Answer in the same response
+- Do not fabricate tool return results (Observations); all tool results are injected by the system
+- Call at most one tool per response
═══════════════════════════════════════════════════════════════
-【章节内容要求】
+[Section Content Requirements]
═══════════════════════════════════════════════════════════════
-1. 内容必须基于工具检索到的模拟数据
-2. 大量引用原文来展示模拟效果
-3. 使用Markdown格式(但禁止使用标题):
- - 使用 **粗体文字** 标记重点(代替子标题)
- - 使用列表(-或1.2.3.)组织要点
- - 使用空行分隔不同段落
- - ❌ 禁止使用 #、##、###、#### 等任何标题语法
-4. 【引用格式规范 - 必须单独成段】
- 引用必须独立成段,前后各有一个空行,不能混在段落中:
-
- ✅ 正确格式:
+1. Content must be based on simulation data retrieved through tools
+2. Extensively quote original text to demonstrate simulation results
+3. Use Markdown formatting (but headings are prohibited):
+ - Use **bold text** to mark key points (instead of sub-headings)
+ - Use lists (- or 1.2.3.) to organize key points
+ - Use blank lines to separate different paragraphs
+ - Do NOT use #, ##, ###, #### or any heading syntax
+4. [Quote Formatting Rules - Must Be Standalone Paragraphs]
+ Quotes must be standalone paragraphs with a blank line before and after, and cannot be mixed into paragraphs:
+
+ Correct format:
```
- 校方的回应被认为缺乏实质内容。
+ The university's response was considered lacking in substance.
- > "校方的应对模式在瞬息万变的社交媒体环境中显得僵化和迟缓。"
+ > "The university's response pattern appeared rigid and slow in the rapidly changing social media environment."
- 这一评价反映了公众的普遍不满。
+ This assessment reflects widespread public dissatisfaction.
```
- ❌ 错误格式:
+ Incorrect format:
```
- 校方的回应被认为缺乏实质内容。> "校方的应对模式..." 这一评价反映了...
+ The university's response was considered lacking in substance. > "The university's response pattern..." This assessment reflects...
```
-5. 保持与其他章节的逻辑连贯性
-6. 【避免重复】仔细阅读下方已完成的章节内容,不要重复描述相同的信息
-7. 【再次强调】不要添加任何标题!用**粗体**代替小节标题"""
+5. Maintain logical coherence with other sections
+6. [Avoid Repetition] Carefully read the completed section content below and do not repeat the same information
+7. [Emphasis] Do not add any headings! Use **bold text** instead of sub-headings"""
SECTION_USER_PROMPT_TEMPLATE = """\
-已完成的章节内容(请仔细阅读,避免重复):
+Completed section content (please read carefully to avoid repetition):
{previous_content}
═══════════════════════════════════════════════════════════════
-【当前任务】撰写章节: {section_title}
+[Current Task] Write section: {section_title}
═══════════════════════════════════════════════════════════════
-【重要提醒】
-1. 仔细阅读上方已完成的章节,避免重复相同的内容!
-2. 开始前必须先调用工具获取模拟数据
-3. 请混合使用不同工具,不要只用一种
-4. 报告内容必须来自检索结果,不要使用自己的知识
+[Important Reminders]
+1. Carefully read the completed sections above to avoid repeating the same content!
+2. You must call tools to obtain simulation data before you begin
+3. Please mix different tools; do not use only one type
+4. Report content must come from retrieval results; do not use your own knowledge
-【⚠️ 格式警告 - 必须遵守】
-- ❌ 不要写任何标题(#、##、###、####都不行)
-- ❌ 不要写"{section_title}"作为开头
-- ✅ 章节标题由系统自动添加
-- ✅ 直接写正文,用**粗体**代替小节标题
+[Format Warning - Must Follow]
+- Do NOT write any headings (#, ##, ###, #### are all prohibited)
+- Do NOT write "{section_title}" as the opening
+- The section title is automatically added by the system
+- Write body text directly, using **bold text** instead of sub-headings
-请开始:
-1. 首先思考(Thought)这个章节需要什么信息
-2. 然后调用工具(Action)获取模拟数据
-3. 收集足够信息后输出 Final Answer(纯正文,无任何标题)"""
+Please begin:
+1. First think (Thought) about what information this section needs
+2. Then call tools (Action) to obtain simulation data
+3. After collecting enough information, output Final Answer (body text only, no headings)
+4. CRITICAL: Write EVERYTHING in English. Translate ALL Chinese quotes and text into English. No Chinese characters allowed in the output."""
-# ── ReACT 循环内消息模板 ──
+# ── ReACT Loop Message Templates ──
REACT_OBSERVATION_TEMPLATE = """\
-Observation(检索结果):
+Observation (retrieval results):
-═══ 工具 {tool_name} 返回 ═══
+=== Tool {tool_name} returned ===
{result}
═══════════════════════════════════════════════════════════════
-已调用工具 {tool_calls_count}/{max_tool_calls} 次(已用: {used_tools_str}){unused_hint}
-- 如果信息充分:以 "Final Answer:" 开头输出章节内容(必须引用上述原文)
-- 如果需要更多信息:调用一个工具继续检索
+Tools called {tool_calls_count}/{max_tool_calls} times (used: {used_tools_str}){unused_hint}
+- If information is sufficient: output section content starting with "Final Answer:" (must quote the original text above)
+- If more information is needed: call a tool to continue retrieval
+- REMINDER: ALL output must be in English. Translate any Chinese text from tool results into English before including it.
═══════════════════════════════════════════════════════════════"""
REACT_INSUFFICIENT_TOOLS_MSG = (
- "【注意】你只调用了{tool_calls_count}次工具,至少需要{min_tool_calls}次。"
- "请再调用工具获取更多模拟数据,然后再输出 Final Answer。{unused_hint}"
+ "[Notice] You have only called tools {tool_calls_count} times; at least {min_tool_calls} calls are required. "
+ "Please call more tools to obtain additional simulation data before outputting Final Answer.{unused_hint}"
)
REACT_INSUFFICIENT_TOOLS_MSG_ALT = (
- "当前只调用了 {tool_calls_count} 次工具,至少需要 {min_tool_calls} 次。"
- "请调用工具获取模拟数据。{unused_hint}"
+ "Currently only {tool_calls_count} tool calls have been made; at least {min_tool_calls} are required. "
+ "Please call tools to obtain simulation data.{unused_hint}"
)
REACT_TOOL_LIMIT_MSG = (
- "工具调用次数已达上限({tool_calls_count}/{max_tool_calls}),不能再调用工具。"
- '请立即基于已获取的信息,以 "Final Answer:" 开头输出章节内容。'
+ "Tool call limit reached ({tool_calls_count}/{max_tool_calls}); no more tool calls allowed. "
+ 'Please immediately output the section content starting with "Final Answer:" based on the information already obtained.'
)
-REACT_UNUSED_TOOLS_HINT = "\n💡 你还没有使用过: {unused_list},建议尝试不同工具获取多角度信息"
+REACT_UNUSED_TOOLS_HINT = "\nTip: You have not yet used: {unused_list}. Consider trying different tools to get multi-angle information."
-REACT_FORCE_FINAL_MSG = "已达到工具调用限制,请直接输出 Final Answer: 并生成章节内容。"
+REACT_FORCE_FINAL_MSG = "Tool call limit reached. Please output Final Answer: directly and generate the section content."
-# ── Chat prompt ──
+# ── Chat Prompt ──
CHAT_SYSTEM_PROMPT_TEMPLATE = """\
-你是一个简洁高效的模拟预测助手。
+You are a concise and efficient simulation prediction assistant.
-【背景】
-预测条件: {simulation_requirement}
+[Background]
+Prediction conditions: {simulation_requirement}
-【已生成的分析报告】
+[Generated Analysis Report]
{report_content}
-【规则】
-1. 优先基于上述报告内容回答问题
-2. 直接回答问题,避免冗长的思考论述
-3. 仅在报告内容不足以回答时,才调用工具检索更多数据
-4. 回答要简洁、清晰、有条理
+[Rules]
+1. Prioritize answering questions based on the report content above
+2. Answer questions directly; avoid lengthy reasoning discussions
+3. Only call tools to retrieve more data when the report content is insufficient to answer
+4. Answers should be concise, clear, and well-organized
-【可用工具】(仅在需要时使用,最多调用1-2次)
+[Available Tools] (use only when needed, call at most 1-2 times)
{tools_description}
-【工具调用格式】
+[Tool Call Format]
-{{"name": "工具名称", "parameters": {{"参数名": "参数值"}}}}
+{{"name": "tool_name", "parameters": {{"param_name": "param_value"}}}}
-【回答风格】
-- 简洁直接,不要长篇大论
-- 使用 > 格式引用关键内容
-- 优先给出结论,再解释原因"""
+[Response Style]
+- Concise and direct; do not write lengthy essays
+- Use > format to quote key content
+- Provide conclusions first, then explain the reasoning"""
-CHAT_OBSERVATION_SUFFIX = "\n\n请简洁回答问题。"
+CHAT_OBSERVATION_SUFFIX = "\n\nPlease answer the question concisely."
# ═══════════════════════════════════════════════════════════════
@@ -1054,11 +1055,11 @@ def _execute_tool(self, tool_name: str, parameters: Dict[str, Any], report_conte
return json.dumps(result, ensure_ascii=False, indent=2)
else:
- return f"未知工具: {tool_name}。请使用以下工具之一: insight_forge, panorama_search, quick_search"
-
+ return f"Unknown tool: {tool_name}. Please use one of: insight_forge, panorama_search, quick_search"
+
except Exception as e:
logger.error(f"工具执行失败: {tool_name}, 错误: {str(e)}")
- return f"工具执行失败: {str(e)}"
+ return f"Tool execution failed: {str(e)}"
# 合法的工具名称集合,用于裸 JSON 兜底解析时校验
VALID_TOOL_NAMES = {"insight_forge", "panorama_search", "quick_search", "interview_agents"}
@@ -1125,12 +1126,12 @@ def _is_valid_tool_call(self, data: dict) -> bool:
def _get_tools_description(self) -> str:
"""生成工具描述文本"""
- desc_parts = ["可用工具:"]
+ desc_parts = ["Available tools:"]
for name, tool in self.tools.items():
params_desc = ", ".join([f"{k}: {v}" for k, v in tool["parameters"].items()])
desc_parts.append(f"- {name}: {tool['description']}")
if params_desc:
- desc_parts.append(f" 参数: {params_desc}")
+ desc_parts.append(f" Parameters: {params_desc}")
return "\n".join(desc_parts)
def plan_outline(
@@ -1151,7 +1152,7 @@ def plan_outline(
logger.info("开始规划报告大纲...")
if progress_callback:
- progress_callback("planning", 0, "正在分析模拟需求...")
+ progress_callback("planning", 0, "Analyzing simulation requirement...")
# 首先获取模拟上下文
context = self.zep_tools.get_simulation_context(
@@ -1160,7 +1161,7 @@ def plan_outline(
)
if progress_callback:
- progress_callback("planning", 30, "正在生成报告大纲...")
+ progress_callback("planning", 30, "Generating report outline...")
system_prompt = PLAN_SYSTEM_PROMPT
user_prompt = PLAN_USER_PROMPT_TEMPLATE.format(
@@ -1182,7 +1183,7 @@ def plan_outline(
)
if progress_callback:
- progress_callback("planning", 80, "正在解析大纲结构...")
+ progress_callback("planning", 80, "Parsing outline structure...")
# 解析大纲
sections = []
@@ -1193,13 +1194,13 @@ def plan_outline(
))
outline = ReportOutline(
- title=response.get("title", "模拟分析报告"),
+ title=response.get("title", "Simulation Analysis Report"),
summary=response.get("summary", ""),
sections=sections
)
if progress_callback:
- progress_callback("planning", 100, "大纲规划完成")
+ progress_callback("planning", 100, "Outline planning complete")
logger.info(f"大纲规划完成: {len(sections)} 个章节")
return outline
@@ -1208,12 +1209,12 @@ def plan_outline(
logger.error(f"大纲规划失败: {str(e)}")
# 返回默认大纲(3个章节,作为fallback)
return ReportOutline(
- title="未来预测报告",
- summary="基于模拟预测的未来趋势与风险分析",
+ title="Future Prediction Report",
+ summary="Future trends and risk analysis based on simulation predictions",
sections=[
- ReportSection(title="预测场景与核心发现"),
- ReportSection(title="人群行为预测分析"),
- ReportSection(title="趋势展望与风险提示")
+ ReportSection(title="Predicted Scenarios and Key Findings"),
+ ReportSection(title="Behavioral Prediction Analysis"),
+ ReportSection(title="Trend Outlook and Risk Warnings")
]
)
@@ -1590,7 +1591,7 @@ def generate_report(
self.console_logger = ReportConsoleLogger(report_id)
ReportManager.update_progress(
- report_id, "pending", 0, "初始化报告...",
+ report_id, "pending", 0, "Initializing report...",
completed_sections=[]
)
ReportManager.save_report(report)
@@ -1598,15 +1599,15 @@ def generate_report(
# 阶段1: 规划大纲
report.status = ReportStatus.PLANNING
ReportManager.update_progress(
- report_id, "planning", 5, "开始规划报告大纲...",
+ report_id, "planning", 5, "Starting report outline planning...",
completed_sections=[]
)
-
+
# 记录规划开始日志
self.report_logger.log_planning_start()
-
+
if progress_callback:
- progress_callback("planning", 0, "开始规划报告大纲...")
+ progress_callback("planning", 0, "Starting report outline planning...")
outline = self.plan_outline(
progress_callback=lambda stage, prog, msg:
@@ -1620,7 +1621,7 @@ def generate_report(
# 保存大纲到文件
ReportManager.save_outline(report_id, outline)
ReportManager.update_progress(
- report_id, "planning", 15, f"大纲规划完成,共{len(outline.sections)}个章节",
+ report_id, "planning", 15, f"Outline planning complete, {len(outline.sections)} sections total",
completed_sections=[]
)
ReportManager.save_report(report)
@@ -1640,16 +1641,16 @@ def generate_report(
# 更新进度
ReportManager.update_progress(
report_id, "generating", base_progress,
- f"正在生成章节: {section.title} ({section_num}/{total_sections})",
+ f"Generating section: {section.title} ({section_num}/{total_sections})",
current_section=section.title,
completed_sections=completed_section_titles
)
-
+
if progress_callback:
progress_callback(
- "generating",
- base_progress,
- f"正在生成章节: {section.title} ({section_num}/{total_sections})"
+ "generating",
+ base_progress,
+ f"Generating section: {section.title} ({section_num}/{total_sections})"
)
# 生成主章节内容
@@ -1687,19 +1688,19 @@ def generate_report(
# 更新进度
ReportManager.update_progress(
- report_id, "generating",
+ report_id, "generating",
base_progress + int(70 / total_sections),
- f"章节 {section.title} 已完成",
+ f"Section {section.title} complete",
current_section=None,
completed_sections=completed_section_titles
)
# 阶段3: 组装完整报告
if progress_callback:
- progress_callback("generating", 95, "正在组装完整报告...")
-
+ progress_callback("generating", 95, "Assembling full report...")
+
ReportManager.update_progress(
- report_id, "generating", 95, "正在组装完整报告...",
+ report_id, "generating", 95, "Assembling full report...",
completed_sections=completed_section_titles
)
@@ -1721,12 +1722,12 @@ def generate_report(
# 保存最终报告
ReportManager.save_report(report)
ReportManager.update_progress(
- report_id, "completed", 100, "报告生成完成",
+ report_id, "completed", 100, "Report generation complete",
completed_sections=completed_section_titles
)
-
+
if progress_callback:
- progress_callback("completed", 100, "报告生成完成")
+ progress_callback("completed", 100, "Report generation complete")
logger.info(f"报告生成完成: {report_id}")
@@ -1750,7 +1751,7 @@ def generate_report(
try:
ReportManager.save_report(report)
ReportManager.update_progress(
- report_id, "failed", -1, f"报告生成失败: {str(e)}",
+ report_id, "failed", -1, f"Report generation failed: {str(e)}",
completed_sections=completed_section_titles
)
except Exception:
diff --git a/backend/app/services/simulation_manager.py b/backend/app/services/simulation_manager.py
index 96c496fd4..5cd8b2a45 100644
--- a/backend/app/services/simulation_manager.py
+++ b/backend/app/services/simulation_manager.py
@@ -260,8 +260,8 @@ def prepare_simulation(
"""
state = self._load_simulation_state(simulation_id)
if not state:
- raise ValueError(f"模拟不存在: {simulation_id}")
-
+ raise ValueError(f"Simulation not found: {simulation_id}")
+
try:
state.status = SimulationStatus.PREPARING
self._save_simulation_state(state)
@@ -270,12 +270,12 @@ def prepare_simulation(
# ========== 阶段1: 读取并过滤实体 ==========
if progress_callback:
- progress_callback("reading", 0, "正在连接Zep图谱...")
+ progress_callback("reading", 0, "Connecting to Zep graph...")
reader = ZepEntityReader()
if progress_callback:
- progress_callback("reading", 30, "正在读取节点数据...")
+ progress_callback("reading", 30, "Reading node data...")
filtered = reader.filter_defined_entities(
graph_id=state.graph_id,
@@ -289,14 +289,14 @@ def prepare_simulation(
if progress_callback:
progress_callback(
"reading", 100,
- f"完成,共 {filtered.filtered_count} 个实体",
+ f"Done, {filtered.filtered_count} entities total",
current=filtered.filtered_count,
total=filtered.filtered_count
)
if filtered.filtered_count == 0:
state.status = SimulationStatus.FAILED
- state.error = "没有找到符合条件的实体,请检查图谱是否正确构建"
+ state.error = "No matching entities found, please check that the graph was built correctly"
self._save_simulation_state(state)
return state
@@ -306,7 +306,7 @@ def prepare_simulation(
if progress_callback:
progress_callback(
"generating_profiles", 0,
- "开始生成...",
+ "Starting generation...",
current=0,
total=total_entities
)
@@ -352,7 +352,7 @@ def profile_progress(current, total, msg):
if progress_callback:
progress_callback(
"generating_profiles", 95,
- "保存Profile文件...",
+ "Saving profile files...",
current=total_entities,
total=total_entities
)
@@ -375,7 +375,7 @@ def profile_progress(current, total, msg):
if progress_callback:
progress_callback(
"generating_profiles", 100,
- f"完成,共 {len(profiles)} 个Profile",
+ f"Done, {len(profiles)} profiles total",
current=len(profiles),
total=len(profiles)
)
@@ -384,7 +384,7 @@ def profile_progress(current, total, msg):
if progress_callback:
progress_callback(
"generating_config", 0,
- "正在分析模拟需求...",
+ "Analyzing simulation requirement...",
current=0,
total=3
)
@@ -394,7 +394,7 @@ def profile_progress(current, total, msg):
if progress_callback:
progress_callback(
"generating_config", 30,
- "正在调用LLM生成配置...",
+ "Calling LLM to generate config...",
current=1,
total=3
)
@@ -413,7 +413,7 @@ def profile_progress(current, total, msg):
if progress_callback:
progress_callback(
"generating_config", 70,
- "正在保存配置文件...",
+ "Saving config file...",
current=2,
total=3
)
@@ -429,7 +429,7 @@ def profile_progress(current, total, msg):
if progress_callback:
progress_callback(
"generating_config", 100,
- "配置生成完成",
+ "Config generation complete",
current=3,
total=3
)
@@ -481,8 +481,8 @@ def get_profiles(self, simulation_id: str, platform: str = "reddit") -> List[Dic
"""获取模拟的Agent Profile"""
state = self._load_simulation_state(simulation_id)
if not state:
- raise ValueError(f"模拟不存在: {simulation_id}")
-
+ raise ValueError(f"Simulation not found: {simulation_id}")
+
sim_dir = self._get_simulation_dir(simulation_id)
profile_path = os.path.join(sim_dir, f"{platform}_profiles.json")
diff --git a/backend/app/services/simulation_runner.py b/backend/app/services/simulation_runner.py
index 8c35380d1..0e2e0499d 100644
--- a/backend/app/services/simulation_runner.py
+++ b/backend/app/services/simulation_runner.py
@@ -333,14 +333,14 @@ def start_simulation(
# 检查是否已在运行
existing = cls.get_run_state(simulation_id)
if existing and existing.runner_status in [RunnerStatus.RUNNING, RunnerStatus.STARTING]:
- raise ValueError(f"模拟已在运行中: {simulation_id}")
+ raise ValueError(f"Simulation is already running: {simulation_id}")
# 加载模拟配置
sim_dir = os.path.join(cls.RUN_STATE_DIR, simulation_id)
config_path = os.path.join(sim_dir, "simulation_config.json")
if not os.path.exists(config_path):
- raise ValueError(f"模拟配置不存在,请先调用 /prepare 接口")
+ raise ValueError("Simulation config not found, please call /prepare first")
with open(config_path, 'r', encoding='utf-8') as f:
config = json.load(f)
@@ -371,7 +371,7 @@ def start_simulation(
# 如果启用图谱记忆更新,创建更新器
if enable_graph_memory_update:
if not graph_id:
- raise ValueError("启用图谱记忆更新时必须提供 graph_id")
+ raise ValueError("graph_id must be provided when enabling graph memory update")
try:
ZepGraphMemoryManager.create_updater(simulation_id, graph_id)
@@ -398,7 +398,7 @@ def start_simulation(
script_path = os.path.join(cls.SCRIPTS_DIR, script_name)
if not os.path.exists(script_path):
- raise ValueError(f"脚本不存在: {script_path}")
+ raise ValueError(f"Script not found: {script_path}")
# 创建动作队列
action_queue = Queue()
@@ -773,10 +773,10 @@ def stop_simulation(cls, simulation_id: str) -> SimulationRunState:
"""停止模拟"""
state = cls.get_run_state(simulation_id)
if not state:
- raise ValueError(f"模拟不存在: {simulation_id}")
-
+ raise ValueError(f"Simulation not found: {simulation_id}")
+
if state.runner_status not in [RunnerStatus.RUNNING, RunnerStatus.PAUSED]:
- raise ValueError(f"模拟未在运行: {simulation_id}, status={state.runner_status}")
+ raise ValueError(f"Simulation is not running: {simulation_id}, status={state.runner_status}")
state.runner_status = RunnerStatus.STOPPING
cls._save_run_state(state)
@@ -1122,7 +1122,7 @@ def cleanup_simulation_logs(cls, simulation_id: str) -> Dict[str, Any]:
sim_dir = os.path.join(cls.RUN_STATE_DIR, simulation_id)
if not os.path.exists(sim_dir):
- return {"success": True, "message": "模拟目录不存在,无需清理"}
+ return {"success": True, "message": "Simulation directory does not exist, nothing to clean"}
cleaned_files = []
errors = []
@@ -1450,12 +1450,12 @@ def interview_agent(
"""
sim_dir = os.path.join(cls.RUN_STATE_DIR, simulation_id)
if not os.path.exists(sim_dir):
- raise ValueError(f"模拟不存在: {simulation_id}")
+ raise ValueError(f"Simulation not found: {simulation_id}")
ipc_client = SimulationIPCClient(sim_dir)
if not ipc_client.check_env_alive():
- raise ValueError(f"模拟环境未运行或已关闭,无法执行Interview: {simulation_id}")
+ raise ValueError(f"Simulation environment is not running or has been closed, cannot execute Interview: {simulation_id}")
logger.info(f"发送Interview命令: simulation_id={simulation_id}, agent_id={agent_id}, platform={platform}")
@@ -1512,12 +1512,12 @@ def interview_agents_batch(
"""
sim_dir = os.path.join(cls.RUN_STATE_DIR, simulation_id)
if not os.path.exists(sim_dir):
- raise ValueError(f"模拟不存在: {simulation_id}")
+ raise ValueError(f"Simulation not found: {simulation_id}")
ipc_client = SimulationIPCClient(sim_dir)
if not ipc_client.check_env_alive():
- raise ValueError(f"模拟环境未运行或已关闭,无法执行Interview: {simulation_id}")
+ raise ValueError(f"Simulation environment is not running or has been closed, cannot execute Interview: {simulation_id}")
logger.info(f"发送批量Interview命令: simulation_id={simulation_id}, count={len(interviews)}, platform={platform}")
@@ -1569,19 +1569,19 @@ def interview_all_agents(
"""
sim_dir = os.path.join(cls.RUN_STATE_DIR, simulation_id)
if not os.path.exists(sim_dir):
- raise ValueError(f"模拟不存在: {simulation_id}")
+ raise ValueError(f"Simulation not found: {simulation_id}")
# 从配置文件获取所有Agent信息
config_path = os.path.join(sim_dir, "simulation_config.json")
if not os.path.exists(config_path):
- raise ValueError(f"模拟配置不存在: {simulation_id}")
+ raise ValueError(f"Simulation config not found: {simulation_id}")
with open(config_path, 'r', encoding='utf-8') as f:
config = json.load(f)
agent_configs = config.get("agent_configs", [])
if not agent_configs:
- raise ValueError(f"模拟配置中没有Agent: {simulation_id}")
+ raise ValueError(f"Simulation config contains no agents: {simulation_id}")
# 构建批量采访列表
interviews = []
@@ -1622,24 +1622,24 @@ def close_simulation_env(
"""
sim_dir = os.path.join(cls.RUN_STATE_DIR, simulation_id)
if not os.path.exists(sim_dir):
- raise ValueError(f"模拟不存在: {simulation_id}")
-
+ raise ValueError(f"Simulation not found: {simulation_id}")
+
ipc_client = SimulationIPCClient(sim_dir)
-
+
if not ipc_client.check_env_alive():
return {
"success": True,
- "message": "环境已经关闭"
+ "message": "Environment is already closed"
}
-
+
logger.info(f"发送关闭环境命令: simulation_id={simulation_id}")
-
+
try:
response = ipc_client.send_close_env(timeout=timeout)
-
+
return {
"success": response.status.value == "completed",
- "message": "环境关闭命令已发送",
+ "message": "Environment close command sent",
"result": response.result,
"timestamp": response.timestamp
}
@@ -1647,7 +1647,7 @@ def close_simulation_env(
# 超时可能是因为环境正在关闭
return {
"success": True,
- "message": "环境关闭命令已发送(等待响应超时,环境可能正在关闭)"
+ "message": "Environment close command sent (response timed out, environment may be closing)"
}
@classmethod
diff --git a/backend/app/services/zep_tools.py b/backend/app/services/zep_tools.py
index 384cf540f..6b242cf6a 100644
--- a/backend/app/services/zep_tools.py
+++ b/backend/app/services/zep_tools.py
@@ -43,10 +43,10 @@ def to_dict(self) -> Dict[str, Any]:
def to_text(self) -> str:
"""转换为文本格式,供LLM理解"""
- text_parts = [f"搜索查询: {self.query}", f"找到 {self.total_count} 条相关信息"]
-
+ text_parts = [f"Search query: {self.query}", f"Found {self.total_count} relevant items"]
+
if self.facts:
- text_parts.append("\n### 相关事实:")
+ text_parts.append("\n### Related facts:")
for i, fact in enumerate(self.facts, 1):
text_parts.append(f"{i}. {fact}")
@@ -73,8 +73,8 @@ def to_dict(self) -> Dict[str, Any]:
def to_text(self) -> str:
"""转换为文本格式"""
- entity_type = next((l for l in self.labels if l not in ["Entity", "Node"]), "未知类型")
- return f"实体: {self.name} (类型: {entity_type})\n摘要: {self.summary}"
+ entity_type = next((l for l in self.labels if l not in ["Entity", "Node"]), "Unknown type")
+ return f"Entity: {self.name} (type: {entity_type})\nSummary: {self.summary}"
@dataclass
@@ -112,14 +112,14 @@ def to_text(self, include_temporal: bool = False) -> str:
"""转换为文本格式"""
source = self.source_node_name or self.source_node_uuid[:8]
target = self.target_node_name or self.target_node_uuid[:8]
- base_text = f"关系: {source} --[{self.name}]--> {target}\n事实: {self.fact}"
-
+ base_text = f"Relation: {source} --[{self.name}]--> {target}\nFact: {self.fact}"
+
if include_temporal:
- valid_at = self.valid_at or "未知"
- invalid_at = self.invalid_at or "至今"
- base_text += f"\n时效: {valid_at} - {invalid_at}"
+ valid_at = self.valid_at or "unknown"
+ invalid_at = self.invalid_at or "present"
+ base_text += f"\nValidity: {valid_at} - {invalid_at}"
if self.expired_at:
- base_text += f" (已过期: {self.expired_at})"
+ base_text += f" (expired: {self.expired_at})"
return base_text
@@ -170,40 +170,40 @@ def to_dict(self) -> Dict[str, Any]:
def to_text(self) -> str:
"""转换为详细的文本格式,供LLM理解"""
text_parts = [
- f"## 未来预测深度分析",
- f"分析问题: {self.query}",
- f"预测场景: {self.simulation_requirement}",
- f"\n### 预测数据统计",
- f"- 相关预测事实: {self.total_facts}条",
- f"- 涉及实体: {self.total_entities}个",
- f"- 关系链: {self.total_relationships}条"
+ f"## Deep Future Prediction Analysis",
+ f"Analysis query: {self.query}",
+ f"Prediction scenario: {self.simulation_requirement}",
+ f"\n### Prediction Data Statistics",
+ f"- Relevant prediction facts: {self.total_facts}",
+ f"- Entities involved: {self.total_entities}",
+ f"- Relationship chains: {self.total_relationships}"
]
-
+
# 子问题
if self.sub_queries:
- text_parts.append(f"\n### 分析的子问题")
+ text_parts.append(f"\n### Sub-queries analyzed")
for i, sq in enumerate(self.sub_queries, 1):
text_parts.append(f"{i}. {sq}")
-
+
# 语义搜索结果
if self.semantic_facts:
- text_parts.append(f"\n### 【关键事实】(请在报告中引用这些原文)")
+ text_parts.append(f"\n### [Key Facts] (please cite these verbatim in the report)")
for i, fact in enumerate(self.semantic_facts, 1):
text_parts.append(f"{i}. \"{fact}\"")
-
+
# 实体洞察
if self.entity_insights:
- text_parts.append(f"\n### 【核心实体】")
+ text_parts.append(f"\n### [Core Entities]")
for entity in self.entity_insights:
- text_parts.append(f"- **{entity.get('name', '未知')}** ({entity.get('type', '实体')})")
+ text_parts.append(f"- **{entity.get('name', 'Unknown')}** ({entity.get('type', 'Entity')})")
if entity.get('summary'):
- text_parts.append(f" 摘要: \"{entity.get('summary')}\"")
+ text_parts.append(f" Summary: \"{entity.get('summary')}\"")
if entity.get('related_facts'):
- text_parts.append(f" 相关事实: {len(entity.get('related_facts', []))}条")
-
+ text_parts.append(f" Related facts: {len(entity.get('related_facts', []))}")
+
# 关系链
if self.relationship_chains:
- text_parts.append(f"\n### 【关系链】")
+ text_parts.append(f"\n### [Relationship Chains]")
for chain in self.relationship_chains:
text_parts.append(f"- {chain}")
@@ -249,32 +249,32 @@ def to_dict(self) -> Dict[str, Any]:
def to_text(self) -> str:
"""转换为文本格式(完整版本,不截断)"""
text_parts = [
- f"## 广度搜索结果(未来全景视图)",
- f"查询: {self.query}",
- f"\n### 统计信息",
- f"- 总节点数: {self.total_nodes}",
- f"- 总边数: {self.total_edges}",
- f"- 当前有效事实: {self.active_count}条",
- f"- 历史/过期事实: {self.historical_count}条"
+ f"## Breadth Search Results (Future Panorama View)",
+ f"Query: {self.query}",
+ f"\n### Statistics",
+ f"- Total nodes: {self.total_nodes}",
+ f"- Total edges: {self.total_edges}",
+ f"- Currently active facts: {self.active_count}",
+ f"- Historical/expired facts: {self.historical_count}"
]
-
+
# 当前有效的事实(完整输出,不截断)
if self.active_facts:
- text_parts.append(f"\n### 【当前有效事实】(模拟结果原文)")
+ text_parts.append(f"\n### [Currently Active Facts] (verbatim simulation results)")
for i, fact in enumerate(self.active_facts, 1):
text_parts.append(f"{i}. \"{fact}\"")
-
+
# 历史/过期事实(完整输出,不截断)
if self.historical_facts:
- text_parts.append(f"\n### 【历史/过期事实】(演变过程记录)")
+ text_parts.append(f"\n### [Historical/Expired Facts] (evolution record)")
for i, fact in enumerate(self.historical_facts, 1):
text_parts.append(f"{i}. \"{fact}\"")
-
+
# 关键实体(完整输出,不截断)
if self.all_nodes:
- text_parts.append(f"\n### 【涉及实体】")
+ text_parts.append(f"\n### [Entities Involved]")
for node in self.all_nodes:
- entity_type = next((l for l in node.labels if l not in ["Entity", "Node"]), "实体")
+ entity_type = next((l for l in node.labels if l not in ["Entity", "Node"]), "Entity")
text_parts.append(f"- **{node.name}** ({entity_type})")
return "\n".join(text_parts)
@@ -303,11 +303,11 @@ def to_dict(self) -> Dict[str, Any]:
def to_text(self) -> str:
text = f"**{self.agent_name}** ({self.agent_role})\n"
# 显示完整的agent_bio,不截断
- text += f"_简介: {self.agent_bio}_\n\n"
+ text += f"_Bio: {self.agent_bio}_\n\n"
text += f"**Q:** {self.question}\n\n"
text += f"**A:** {self.response}\n"
if self.key_quotes:
- text += "\n**关键引言:**\n"
+ text += "\n**Key quotes:**\n"
for quote in self.key_quotes:
# 清理各种引号
clean_quote = quote.replace('\u201c', '').replace('\u201d', '').replace('"', '')
@@ -374,25 +374,25 @@ def to_dict(self) -> Dict[str, Any]:
def to_text(self) -> str:
"""转换为详细的文本格式,供LLM理解和报告引用"""
text_parts = [
- "## 深度采访报告",
- f"**采访主题:** {self.interview_topic}",
- f"**采访人数:** {self.interviewed_count} / {self.total_agents} 位模拟Agent",
- "\n### 采访对象选择理由",
- self.selection_reasoning or "(自动选择)",
+ "## In-Depth Interview Report",
+ f"**Interview topic:** {self.interview_topic}",
+ f"**Interviews conducted:** {self.interviewed_count} / {self.total_agents} simulated agents",
+ "\n### Agent selection reasoning",
+ self.selection_reasoning or "(auto-selected)",
"\n---",
- "\n### 采访实录",
+ "\n### Interview transcripts",
]
if self.interviews:
for i, interview in enumerate(self.interviews, 1):
- text_parts.append(f"\n#### 采访 #{i}: {interview.agent_name}")
+ text_parts.append(f"\n#### Interview #{i}: {interview.agent_name}")
text_parts.append(interview.to_text())
text_parts.append("\n---")
else:
- text_parts.append("(无采访记录)\n\n---")
+ text_parts.append("(No interview records)\n\n---")
- text_parts.append("\n### 采访摘要与核心观点")
- text_parts.append(self.summary or "(无摘要)")
+ text_parts.append("\n### Interview summary and key viewpoints")
+ text_parts.append(self.summary or "(No summary)")
return "\n".join(text_parts)
@@ -424,7 +424,7 @@ class ZepToolsService:
def __init__(self, api_key: Optional[str] = None, llm_client: Optional[LLMClient] = None):
self.api_key = api_key or Config.ZEP_API_KEY
if not self.api_key:
- raise ValueError("ZEP_API_KEY 未配置")
+ raise ValueError("ZEP_API_KEY not configured")
self.client = Zep(api_key=self.api_key)
# LLM客户端用于InsightForge生成子问题
@@ -1046,7 +1046,7 @@ def insight_forge(
node = self.get_node_detail(uuid)
if node:
node_map[uuid] = node
- entity_type = next((l for l in node.labels if l not in ["Entity", "Node"]), "实体")
+ entity_type = next((l for l in node.labels if l not in ["Entity", "Node"]), "Entity")
# 获取该实体相关的所有事实(不截断)
related_facts = [
@@ -1200,8 +1200,8 @@ def panorama_search(
if is_historical:
# 历史/过期事实,添加时间标记
- valid_at = edge.valid_at or "未知"
- invalid_at = edge.invalid_at or edge.expired_at or "未知"
+ valid_at = edge.valid_at or "unknown"
+ invalid_at = edge.invalid_at or edge.expired_at or "unknown"
fact_with_time = f"[{valid_at} - {invalid_at}] {edge.fact}"
historical_facts.append(fact_with_time)
else:
@@ -1318,7 +1318,7 @@ def interview_agents(
if not profiles:
logger.warning(f"未找到模拟 {simulation_id} 的人设文件")
- result.summary = "未找到可采访的Agent人设文件"
+ result.summary = "No agent profile files found for interview"
return result
result.total_agents = len(profiles)
@@ -1350,15 +1350,15 @@ def interview_agents(
# 添加优化前缀,约束Agent回复格式
INTERVIEW_PROMPT_PREFIX = (
- "你正在接受一次采访。请结合你的人设、所有的过往记忆与行动,"
- "以纯文本方式直接回答以下问题。\n"
- "回复要求:\n"
- "1. 直接用自然语言回答,不要调用任何工具\n"
- "2. 不要返回JSON格式或工具调用格式\n"
- "3. 不要使用Markdown标题(如#、##、###)\n"
- "4. 按问题编号逐一回答,每个回答以「问题X:」开头(X为问题编号)\n"
- "5. 每个问题的回答之间用空行分隔\n"
- "6. 回答要有实质内容,每个问题至少回答2-3句话\n\n"
+ "You are being interviewed. Based on your persona, all past memories and actions, "
+ "please answer the following questions directly in plain text.\n"
+ "Response requirements:\n"
+ "1. Answer directly in natural language; do not call any tools\n"
+ "2. Do not return JSON format or tool call format\n"
+ "3. Do not use Markdown headings (such as #, ##, ###)\n"
+ "4. Answer each question in order, starting each answer with 'Question X:' (X is the question number)\n"
+ "5. Separate answers to different questions with blank lines\n"
+ "6. Answers should have substantive content; answer each question with at least 2-3 sentences\n\n"
)
optimized_prompt = f"{INTERVIEW_PROMPT_PREFIX}{combined_prompt}"
@@ -1387,9 +1387,9 @@ def interview_agents(
# 检查API调用是否成功
if not api_result.get("success", False):
- error_msg = api_result.get("error", "未知错误")
+ error_msg = api_result.get("error", "Unknown error")
logger.warning(f"采访API返回失败: {error_msg}")
- result.summary = f"采访API调用失败:{error_msg}。请检查OASIS模拟环境状态。"
+ result.summary = f"Interview API call failed: {error_msg}. Please check OASIS simulation environment status."
return result
# Step 5: 解析API返回结果,构建AgentInterview对象
@@ -1400,7 +1400,7 @@ def interview_agents(
for i, agent_idx in enumerate(selected_indices):
agent = selected_agents[i]
agent_name = agent.get("realname", agent.get("username", f"Agent_{agent_idx}"))
- agent_role = agent.get("profession", "未知")
+ agent_role = agent.get("profession", "Unknown")
agent_bio = agent.get("bio", "")
# 获取该Agent在两个平台的采访结果
@@ -1415,9 +1415,9 @@ def interview_agents(
reddit_response = self._clean_tool_call_response(reddit_response)
# 始终输出双平台标记
- twitter_text = twitter_response if twitter_response else "(该平台未获得回复)"
- reddit_text = reddit_response if reddit_response else "(该平台未获得回复)"
- response_text = f"【Twitter平台回答】\n{twitter_text}\n\n【Reddit平台回答】\n{reddit_text}"
+ twitter_text = twitter_response if twitter_response else "(No response from this platform)"
+ reddit_text = reddit_response if reddit_response else "(No response from this platform)"
+ response_text = f"[Twitter Platform Response]\n{twitter_text}\n\n[Reddit Platform Response]\n{reddit_text}"
# 提取关键引言(从两个平台的回答中)
import re
@@ -1462,13 +1462,13 @@ def interview_agents(
except ValueError as e:
# 模拟环境未运行
logger.warning(f"采访API调用失败(环境未运行?): {e}")
- result.summary = f"采访失败:{str(e)}。模拟环境可能已关闭,请确保OASIS环境正在运行。"
+ result.summary = f"Interview failed: {str(e)}. The simulation environment may have been closed, please ensure OASIS environment is running."
return result
except Exception as e:
logger.error(f"采访API调用异常: {e}")
import traceback
logger.error(traceback.format_exc())
- result.summary = f"采访过程发生错误:{str(e)}"
+ result.summary = f"An error occurred during the interview: {str(e)}"
return result
# Step 6: 生成采访摘要
@@ -1539,7 +1539,7 @@ def _load_agent_profiles(self, simulation_id: str) -> List[Dict[str, Any]]:
"username": row.get("username", ""),
"bio": row.get("description", ""),
"persona": row.get("user_char", ""),
- "profession": "未知"
+ "profession": "Unknown"
})
logger.info(f"从 twitter_profiles.csv 加载了 {len(profiles)} 个人设")
return profiles
@@ -1571,7 +1571,7 @@ def _select_agents_for_interview(
summary = {
"index": i,
"name": profile.get("realname", profile.get("username", f"Agent_{i}")),
- "profession": profile.get("profession", "未知"),
+ "profession": profile.get("profession", "Unknown"),
"bio": profile.get("bio", "")[:200],
"interested_topics": profile.get("interested_topics", [])
}
@@ -1612,7 +1612,7 @@ def _select_agents_for_interview(
)
selected_indices = response.get("selected_indices", [])[:max_agents]
- reasoning = response.get("reasoning", "基于相关性自动选择")
+ reasoning = response.get("reasoning", "Auto-selected based on relevance")
# 获取选中的Agent完整信息
selected_agents = []
@@ -1629,7 +1629,7 @@ def _select_agents_for_interview(
# 降级:选择前N个
selected = profiles[:max_agents]
indices = list(range(min(max_agents, len(profiles))))
- return selected, indices, "使用默认选择策略"
+ return selected, indices, "Using default selection strategy"
def _generate_interview_questions(
self,
@@ -1639,7 +1639,7 @@ def _generate_interview_questions(
) -> List[str]:
"""使用LLM生成采访问题"""
- agent_roles = [a.get("profession", "未知") for a in selected_agents]
+ agent_roles = [a.get("profession", "Unknown") for a in selected_agents]
system_prompt = """你是一个专业的记者/采访者。根据采访需求,生成3-5个深度采访问题。
@@ -1688,7 +1688,7 @@ def _generate_interview_summary(
"""生成采访摘要"""
if not interviews:
- return "未完成任何采访"
+ return "No interviews completed"
# 收集所有采访内容
interview_texts = []
@@ -1732,4 +1732,4 @@ def _generate_interview_summary(
except Exception as e:
logger.warning(f"生成采访摘要失败: {e}")
# 降级:简单拼接
- return f"共采访了{len(interviews)}位受访者,包括:" + "、".join([i.agent_name for i in interviews])
+ return f"Interviewed {len(interviews)} respondents, including: " + ", ".join([i.agent_name for i in interviews])
diff --git a/frontend/index.html b/frontend/index.html
index 009c924a4..4f24f76ee 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -1,5 +1,5 @@
-
+
@@ -7,8 +7,8 @@
-
- MiroFish - 预测万物
+
+ MiroFish - Predict Anything
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index 8c4fa710d..3edf33957 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -11,6 +11,7 @@
"axios": "^1.13.2",
"d3": "^7.9.0",
"vue": "^3.5.24",
+ "vue-i18n": "^9.14.5",
"vue-router": "^4.6.3"
},
"devDependencies": {
@@ -506,6 +507,50 @@
"node": ">=18"
}
},
+ "node_modules/@intlify/core-base": {
+ "version": "9.14.5",
+ "resolved": "https://registry.npmjs.org/@intlify/core-base/-/core-base-9.14.5.tgz",
+ "integrity": "sha512-5ah5FqZG4pOoHjkvs8mjtv+gPKYU0zCISaYNjBNNqYiaITxW8ZtVih3GS/oTOqN8d9/mDLyrjD46GBApNxmlsA==",
+ "license": "MIT",
+ "dependencies": {
+ "@intlify/message-compiler": "9.14.5",
+ "@intlify/shared": "9.14.5"
+ },
+ "engines": {
+ "node": ">= 16"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/kazupon"
+ }
+ },
+ "node_modules/@intlify/message-compiler": {
+ "version": "9.14.5",
+ "resolved": "https://registry.npmjs.org/@intlify/message-compiler/-/message-compiler-9.14.5.tgz",
+ "integrity": "sha512-IHzgEu61/YIpQV5Pc3aRWScDcnFKWvQA9kigcINcCBXN8mbW+vk9SK+lDxA6STzKQsVJxUPg9ACC52pKKo3SVQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@intlify/shared": "9.14.5",
+ "source-map-js": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 16"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/kazupon"
+ }
+ },
+ "node_modules/@intlify/shared": {
+ "version": "9.14.5",
+ "resolved": "https://registry.npmjs.org/@intlify/shared/-/shared-9.14.5.tgz",
+ "integrity": "sha512-9gB+E53BYuAEMhbCAxVgG38EZrk59sxBtv3jSizNL2hEWlgjBjAw1AwpLHtNaeda12pe6W20OGEa0TwuMSRbyQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 16"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/kazupon"
+ }
+ },
"node_modules/@jridgewell/sourcemap-codec": {
"version": "1.5.5",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
@@ -2035,6 +2080,27 @@
}
}
},
+ "node_modules/vue-i18n": {
+ "version": "9.14.5",
+ "resolved": "https://registry.npmjs.org/vue-i18n/-/vue-i18n-9.14.5.tgz",
+ "integrity": "sha512-0jQ9Em3ymWngyiIkj0+c/k7WgaPO+TNzjKSNq9BvBQaKJECqn9cd9fL4tkDhB5G1QBskGl9YxxbDAhgbFtpe2g==",
+ "deprecated": "v9 and v10 no longer supported. please migrate to v11. about maintenance status, see https://vue-i18n.intlify.dev/guide/maintenance.html",
+ "license": "MIT",
+ "dependencies": {
+ "@intlify/core-base": "9.14.5",
+ "@intlify/shared": "9.14.5",
+ "@vue/devtools-api": "^6.5.0"
+ },
+ "engines": {
+ "node": ">= 16"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/kazupon"
+ },
+ "peerDependencies": {
+ "vue": "^3.0.0"
+ }
+ },
"node_modules/vue-router": {
"version": "4.6.3",
"resolved": "https://registry.npmjs.org/vue-router/-/vue-router-4.6.3.tgz",
diff --git a/frontend/package.json b/frontend/package.json
index f7e995a14..7e05e8918 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -12,6 +12,7 @@
"axios": "^1.13.2",
"d3": "^7.9.0",
"vue": "^3.5.24",
+ "vue-i18n": "^9.14.5",
"vue-router": "^4.6.3"
},
"devDependencies": {
diff --git a/frontend/src/components/GraphPanel.vue b/frontend/src/components/GraphPanel.vue
index 314c966e4..d5e68cb4f 100644
--- a/frontend/src/components/GraphPanel.vue
+++ b/frontend/src/components/GraphPanel.vue
@@ -4,11 +4,11 @@
Graph Relationship Visualization
@@ -27,7 +27,7 @@
- {{ isSimulating ? 'GraphRAG长短期记忆实时更新中' : '实时更新中...' }}
+ {{ isSimulating ? $t('graphPanel.hintSimulation') : $t('graphPanel.hintBuild') }}
@@ -39,8 +39,8 @@
- 还有少量内容处理中,建议稍后手动刷新图谱
-