diff --git a/config/agent_fill_fields_template.txt b/config/agent_fill_fields_template.txt new file mode 100644 index 0000000..2b4979a --- /dev/null +++ b/config/agent_fill_fields_template.txt @@ -0,0 +1,71 @@ +## 任务背景 + +### 产品基本信息 +- **产品名称:** {{product_name}} +- **产品类别:** {{category}} +- **子类别:** {{subcategory}} + +### 相关内容数据ID +上一步已筛选出以下与产品直接相关且对参数提取有用的内容库数据ID: +{{relevant_content_ids}} + +## 任务要求 + +请完成以下工作: + +### 1. 获取对应类别的字段配置 +首先,请访问 ParamHub API 文档获取对应类别的字段定义: +- API文档地址:http://192.168.2.8:12007/hz4th_coder/param-hub-python/src/branch/master/API.md +- 根据产品类别({{category}})确定应该使用哪个API: + - AI模型 → `/api/models` + - GPU → `/api/gpus` + - CPU → `/api/cpus` + - 其他动态分类 → `/api/items/{category_id}` + +### 2. 从内容库获取数据内容 +根据上述数据ID,从内容库中获取每条数据的完整内容。 + +### 3. 整理产品参数 +根据获取到的内容,提取并整理产品的各项参数,严格按照API文档中定义的字段格式填充。 + +### 4. 提交到审核系统 +使用以下命令提交到ParamHub审核系统: + +```bash +# 先登录获取cookie +curl -c /tmp/paramhub_cookie.txt -X POST "http://localhost:16041/login" \ + -H "Content-Type: application/json" \ + -d '{"password": "admin123"}' + +# 然后提交产品数据(根据类别选择对应的API) +curl -b /tmp/paramhub_cookie.txt -X POST "http://localhost:16041/api/{对应类别API}" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "{{product_name}}", + "visible": true, + "is_pinned": false, + // ... 其他字段根据API文档填充 + }' +``` + +### 5. 输出要求 +请以JSON格式输出执行结果: +```json +{ + "success": true, + "review_id": "审核ID(如果提交成功)", + "submitted_data": { + "name": "产品名称", + "field1": "值1", + "field2": "值2" + }, + "data_sources": [数据ID列表], + "message": "执行说明" +} +``` + +**注意:** +- 严格按照API文档的字段定义填充数据 +- 不要编造或推测任何参数,只使用内容库中实际存在的信息 +- 如果某些字段无法从内容中提取,可以留空或填写默认值 +- 提交成功后记录返回的review_id diff --git a/routes/process_monitor.py b/routes/process_monitor.py index 44e7cfc..d14e12e 100644 --- a/routes/process_monitor.py +++ b/routes/process_monitor.py @@ -258,3 +258,83 @@ def preview_agent_template(): except Exception as e: logger.error(f"预览模板失败: {e}") return jsonify({'success': False, 'error': str(e)}), 500 + + +# ===== 步骤5填充字段模板 API ===== + +FILL_FIELDS_TEMPLATE_FILE = os.path.join(TEMPLATE_DIR, 'agent_fill_fields_template.txt') + + +@bp.route('/fill-fields-template', methods=['GET']) +def get_fill_fields_template(): + """获取步骤5填充字段任务文本模板""" + try: + if os.path.exists(FILL_FIELDS_TEMPLATE_FILE): + with open(FILL_FIELDS_TEMPLATE_FILE, 'r', encoding='utf-8') as f: + template = f.read() + return jsonify({ + 'success': True, + 'template': template + }) + else: + return jsonify({ + 'success': False, + 'error': '模板文件不存在' + }), 404 + except Exception as e: + logger.error(f"获取填充字段模板失败: {e}") + return jsonify({'success': False, 'error': str(e)}), 500 + + +@bp.route('/fill-fields-template', methods=['POST']) +def save_fill_fields_template(): + """保存步骤5填充字段任务文本模板""" + try: + data = request.get_json() + template = data.get('template', '') + + if not template: + return jsonify({'success': False, 'error': '模板内容不能为空'}), 400 + + os.makedirs(TEMPLATE_DIR, exist_ok=True) + with open(FILL_FIELDS_TEMPLATE_FILE, 'w', encoding='utf-8') as f: + f.write(template) + + return jsonify({ + 'success': True, + 'message': '模板已保存' + }) + except Exception as e: + logger.error(f"保存填充字段模板失败: {e}") + return jsonify({'success': False, 'error': str(e)}), 500 + + +@bp.route('/fill-fields-template/preview', methods=['POST']) +def preview_fill_fields_template(): + """预览填充后的步骤5任务文本""" + try: + data = request.get_json() + product_name = data.get('product_name', '示例产品') + category = data.get('category', '示例类别') + subcategory = data.get('subcategory', '示例子类别') + + # 读取模板 + if os.path.exists(FILL_FIELDS_TEMPLATE_FILE): + with open(FILL_FIELDS_TEMPLATE_FILE, 'r', encoding='utf-8') as f: + template = f.read() + else: + return jsonify({'success': False, 'error': '模板文件不存在'}), 404 + + # 填充示例数据 + filled = template.replace('{{product_name}}', product_name) + filled = filled.replace('{{category}}', category) + filled = filled.replace('{{subcategory}}', subcategory or '无') + filled = filled.replace('{{relevant_content_ids}}', 'ID 101: 示例相关文章A\nID 102: 示例相关文章B\nID 103: 示例相关文章C') + + return jsonify({ + 'success': True, + 'preview': filled + }) + except Exception as e: + logger.error(f"预览填充字段模板失败: {e}") + return jsonify({'success': False, 'error': str(e)}), 500 diff --git a/services/process_monitor.py b/services/process_monitor.py index 002d901..8663596 100644 --- a/services/process_monitor.py +++ b/services/process_monitor.py @@ -21,7 +21,7 @@ PROCESS_STEPS = [ {'num': 2, 'name': '搜索互联网', 'description': '从互联网搜索最新数据'}, {'num': 3, 'name': '抓取网页内容', 'description': '抓取搜索结果网页的详细内容'}, {'num': 4, 'name': '提取产品数据(智能体)', 'description': '调用hz4th_editor智能体提取产品相关内容'}, - {'num': 5, 'name': '填充字段', 'description': '根据分类字段配置填充数据'}, + {'num': 5, 'name': '填充字段(智能体)', 'description': '调用hz4th_editor智能体整理产品数据并提交审核'}, {'num': 6, 'name': '提交审核', 'description': '提交到ParamHub待审核区'}, ] @@ -227,23 +227,76 @@ class ProcessMonitor: except Exception as e: self._fail_step(session_id, 4, str(e)) - # 步骤5: 填充字段 + # 步骤5: 填充字段并提交审核(调用智能体执行) if not self._check_pause(session_id) and all_data['extracted_data']: - self._start_step(session_id, product_name, 5, '填充字段') + self._start_step(session_id, product_name, 5, '填充字段并提交(智能体)') try: - filled = self._fill_fields(all_data['extracted_data'], category, subcategory) - all_data['filled_data'] = filled + # 构建任务文本 + fill_task_text = self._build_fill_fields_task( + product_name, category, subcategory, all_data['extracted_data'] + ) - if filled: - self._complete_step(session_id, 5, {'filled': True}) + # 调用智能体 + fill_agent_result = self._call_agent(fill_task_text) + + if fill_agent_result.get('success'): + fill_parsed = self._parse_fill_agent_response(fill_agent_result.get('output', '')) + + if fill_parsed and fill_parsed.get('success'): + review_id = fill_parsed.get('review_id') + submitted_data = fill_parsed.get('submitted_data', {}) + + all_data['filled_data'] = submitted_data + + self._complete_step(session_id, 5, { + 'filled': True, + 'agent': 'hz4th_editor', + 'task_text': fill_task_text, + 'review_id': review_id, + 'submitted_data': submitted_data, + 'agent_output': fill_agent_result.get('output', '')[:2000] + }) + + # 如果智能体返回了review_id,直接标记步骤6完成 + if review_id: + result['success'] = True + result['review_id'] = review_id + + db.update_session_status(session_id, 'completed', + review_id=review_id, + result=json.dumps(result, ensure_ascii=False)) + + db.add_process_history( + product_name=product_name, + category=category, + subcategory=subcategory, + status='submitted', + review_id=review_id, + details=all_data + ) + logger.info(f"[{session_id}] 步骤5完成: 智能体提交成功, review_id={review_id}") + else: + self._complete_step(session_id, 5, { + 'filled': True, + 'agent': 'hz4th_editor', + 'task_text': fill_task_text, + 'submitted_data': submitted_data, + 'message': '数据已整理但未获取到review_id', + 'agent_output': fill_agent_result.get('output', '')[:2000] + }) + result['message'] = '数据已整理但提交状态未知' + else: + self._fail_step(session_id, 5, f"智能体执行失败: {fill_parsed.get('message', '未知错误') if fill_parsed else '解析失败'}") + result['message'] = f'智能体执行失败' else: - self._fail_step(session_id, 5, '填充数据失败') + self._fail_step(session_id, 5, f"智能体调用失败: {fill_agent_result.get('error', '未知错误')}") + result['message'] = f'智能体调用失败: {fill_agent_result.get("error")}' except Exception as e: self._fail_step(session_id, 5, str(e)) - # 步骤6: 提交审核 - if not self._check_pause(session_id) and all_data['filled_data']: - self._start_step(session_id, product_name, 6, '提交审核') + # 步骤6: 确认提交结果(如果步骤5未获取到review_id,尝试本地提交) + if not self._check_pause(session_id) and all_data['filled_data'] and not result.get('review_id'): + self._start_step(session_id, product_name, 6, '确认提交结果') try: category_type = self._get_category_type(category) success, review_id_or_error = paramhub_client.submit_for_review( @@ -269,7 +322,7 @@ class ProcessMonitor: review_id=review_id_or_error, details=all_data ) - logger.info(f"[{session_id}] 步骤6完成: 提交成功") + logger.info(f"[{session_id}] 步骤6完成: 本地提交成功") else: self._fail_step(session_id, 6, review_id_or_error) db.update_session_status(session_id, 'failed') @@ -493,6 +546,96 @@ class ProcessMonitor: return None + def _build_fill_fields_task(self, product_name, category, subcategory, extracted_data): + """构建步骤5填充字段的智能体任务文本""" + # 读取模板 + template_file = os.path.join( + os.path.dirname(os.path.dirname(__file__)), + 'config', 'agent_fill_fields_template.txt' + ) + + if os.path.exists(template_file): + with open(template_file, 'r', encoding='utf-8') as f: + template = f.read() + else: + # 默认模板 + template = ( + "请根据内容库数据ID {{relevant_content_ids}} 整理产品「{{product_name}}」的参数并提交审核。\n" + "类别: {{category}} / {{subcategory}}\n" + "参考API文档: http://192.168.2.8:12007/hz4th_coder/param-hub-python/src/branch/master/API.md" + ) + + # 构建相关内容ID列表 + relevant_ids = extracted_data.get('relevant_ids', []) + relevant_contents = extracted_data.get('relevant_contents', []) + + if relevant_contents: + content_lines = [] + for item in relevant_contents: + aid = item.get('id', '') + title = item.get('title', '') + content_lines.append(f"ID {aid}: {title}") + relevant_text = '\n'.join(content_lines) + elif relevant_ids: + relevant_text = '\n'.join([f"ID {aid}" for aid in relevant_ids]) + else: + relevant_text = '(无相关内容ID)' + + # 填充模板 + task = template.replace('{{product_name}}', product_name or '未知') + task = task.replace('{{category}}', category or '未分类') + task = task.replace('{{subcategory}}', subcategory or '无') + task = task.replace('{{relevant_content_ids}}', relevant_text) + + return task + + def _parse_fill_agent_response(self, output): + """解析步骤5智能体返回的结果""" + if not output: + return None + + import re + + parsed_data = None + + # 查找JSON块 + json_match = re.search(r'```(?:json)?\s*(\{.*?\})\s*```', output, re.DOTALL) + if json_match: + try: + parsed_data = json.loads(json_match.group(1)) + except json.JSONDecodeError: + pass + + # 尝试直接解析整个输出为JSON + if not parsed_data: + try: + parsed_data = json.loads(output) + except json.JSONDecodeError: + pass + + if parsed_data: + return { + 'success': parsed_data.get('success', False), + 'review_id': parsed_data.get('review_id'), + 'submitted_data': parsed_data.get('submitted_data', {}), + 'data_sources': parsed_data.get('data_sources', []), + 'message': parsed_data.get('message', ''), + 'raw_output': output + } + + # 尝试从文本中提取review_id + review_match = re.search(r'review[_-]?id[\s:]*([\w-]+)', output, re.I) + if review_match: + return { + 'success': True, + 'review_id': review_match.group(1), + 'submitted_data': {}, + 'message': '从输出中提取到review_id', + 'raw_output': output + } + + return None + def _extract_data(self, product_name, all_data): """提取产品数据(备用,已被智能体替代)""" all_content = [] diff --git a/static/js/process.js b/static/js/process.js index c156a13..d6ba85a 100644 --- a/static/js/process.js +++ b/static/js/process.js @@ -10,6 +10,7 @@ document.addEventListener('DOMContentLoaded', () => { loadActiveProcesses(); loadHistory(); loadAgentTemplate(); + loadFillFieldsTemplate(); // 启动自动刷新(每2秒) startAutoRefresh(); @@ -508,4 +509,82 @@ async function doPreview() { } catch (error) { document.getElementById('template-preview-content').textContent = '预览失败: ' + error.message; } -} \ No newline at end of file +} +// ===== 步骤5填充字段模板 ===== + +// 加载步骤5模板 +async function loadFillFieldsTemplate() { + try { + const response = await fetch(`${API_BASE}/api/process/fill-fields-template`); + const data = await response.json(); + + if (data.success) { + document.getElementById('fill-fields-template-editor').value = data.template; + } else { + document.getElementById('fill-fields-template-editor').value = '// 模板加载失败: ' + (data.error || '未知错误'); + } + } catch (error) { + console.error('加载填充字段模板失败:', error); + document.getElementById('fill-fields-template-editor').value = '// 加载模板失败: ' + error.message; + } +} + +// 保存步骤5模板 +async function saveFillFieldsTemplate() { + const template = document.getElementById('fill-fields-template-editor').value; + + if (!template.trim()) { + showToast('模板内容不能为空', 'error'); + return; + } + + try { + const response = await fetch(`${API_BASE}/api/process/fill-fields-template`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ template }) + }); + const data = await response.json(); + + if (data.success) { + showToast('步骤5模板已保存 ✓', 'success'); + } else { + showToast('保存失败: ' + data.error, 'error'); + } + } catch (error) { + showToast('保存失败: ' + error.message, 'error'); + } +} + +// 预览步骤5模板 +function previewFillFieldsTemplate() { + document.getElementById('template-preview-modal').classList.add('active'); + doFillFieldsPreview(); +} + +// 执行步骤5预览 +async function doFillFieldsPreview() { + const product = document.getElementById('preview-product').value || '示例产品'; + const category = document.getElementById('preview-category').value || 'AI模型'; + + try { + const response = await fetch(`${API_BASE}/api/process/fill-fields-template/preview`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + product_name: product, + category: category, + subcategory: '' + }) + }); + const data = await response.json(); + + if (data.success) { + document.getElementById('template-preview-content').textContent = data.preview; + } else { + document.getElementById('template-preview-content').textContent = '预览失败: ' + data.error; + } + } catch (error) { + document.getElementById('template-preview-content').textContent = '预览失败: ' + error.message; + } +} diff --git a/templates/process.html b/templates/process.html index e3b9d97..a4b3fd5 100644 --- a/templates/process.html +++ b/templates/process.html @@ -52,7 +52,7 @@
-

智能体任务文本模板(步骤4:提取产品数据)

+

步骤4:提取产品数据 - 智能体任务模板

- + +
+
+ + +
+
+

步骤5:填充字段并提交 - 智能体任务模板

+
+ + +
+
+
+
+

说明:此模板用于步骤5「填充字段并提交审核」中调用智能体 hz4th_editor 的任务文本。

+

可用变量: + {{product_name}} 产品名称、 + {{category}} 类别、 + {{subcategory}} 子类别、 + {{relevant_content_ids}} 上一步筛选的相关内容数据ID +

+

任务目标:智能体根据API文档获取字段定义,整理产品参数,并通过API提交到ParamHub审核系统。

+
+