harnessed_reasoning/wwwroot/api/reasoning_submit.dspy
yumoqing c36477c9cb fix: improve LLM call error handling and plan parsing
- Add detailed logging to _llm_call method
- Improve _parse_plan_json to handle more LLM response formats
- Show LLM error messages in reasoning_submit.dspy
- Better error handling and fallback for JSON parsing
2026-05-07 14:51:44 +08:00

72 lines
2.9 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Submit reasoning request and return results"""
import json, time, uuid
result = {'widgettype': 'Message', 'options': {'title': 'Error', 'message': '推理请求失败', 'type': 'error'}}
try:
request_text = params_kw.get('request', '').strip()
if not request_text:
result['options'] = {'title': 'Error', 'message': '请输入推理请求', 'type': 'error'}
else:
user_id = await get_user()
execute_immediately = params_kw.get('execute_immediately', '1') == '1'
# Call the reasoning engine from ServerEnv
reasoning_result = await hermes_reason_and_execute(
request=request_text,
execute_immediately=execute_immediately
)
if reasoning_result.get('success'):
# Build result widget showing reasoning output
analysis = reasoning_result.get('analysis', '')
llm_error = reasoning_result.get('llm_error', '')
plan_items = []
for step in reasoning_result.get('execution_plan', []):
plan_items.append(f"步骤{step.get('step_number', '?')}: {step.get('description', '')}")
plan_text = '\n'.join(plan_items) if plan_items else '无执行计划'
safety_text = '\n'.join(reasoning_result.get('safety_violations', [])) or '无安全风险'
status = reasoning_result.get('status', 'unknown')
summary = (
f"请求: {request_text}\n\n"
f"分析: {analysis}\n\n"
f"上下文: {reasoning_result.get('context_summary', '')}\n\n"
f"置信度: {reasoning_result.get('confidence_score', 0):.0%}\n\n"
f"执行计划:\n{plan_text}\n\n"
f"安全检查:\n{safety_text}\n\n"
f"状态: {status}"
)
# Show LLM error if any
if llm_error:
summary += f"\n\nLLM 错误: {llm_error}"
if reasoning_result.get('execution_results'):
summary += f"\n\n执行结果:\n{json.dumps(reasoning_result['execution_results'], ensure_ascii=False, indent=2)}"
msg_type = 'success' if not llm_error else 'warning'
result = {
'widgettype': 'Message',
'options': {
'title': '推理完成',
'message': summary,
'type': msg_type
}
}
else:
result['options'] = {
'title': '推理失败',
'message': reasoning_result.get('error', '未知错误'),
'type': 'error'
}
except Exception as e:
result['options'] = {'title': 'Error', 'message': '推理异常: ' + str(e), 'type': 'error'}
return json.dumps(result, ensure_ascii=False)