61 lines
2.0 KiB
Python
61 lines
2.0 KiB
Python
from django.shortcuts import render
|
||
|
||
from agent_core.orchestrator import run_agent
|
||
from agent_core.results import AgentResult
|
||
from apps.audit.services import create_audit_log
|
||
from apps.documents.models import UploadedDocument
|
||
from apps.scenarios.services import ScenarioNotFound, get_scenario
|
||
|
||
from .forms import ChatForm
|
||
|
||
|
||
def index(request, scenario_id: str):
|
||
# View 只负责请求编排、表单校验和模板渲染。
|
||
# 具体 Agent 执行、审计写入和文档筛选规则分别交给独立模块处理。
|
||
try:
|
||
scenario = get_scenario(scenario_id)
|
||
except ScenarioNotFound:
|
||
return render(
|
||
request,
|
||
"chat/index.html",
|
||
{
|
||
"scenario": None,
|
||
"form": ChatForm(),
|
||
"error": "场景不存在,请返回首页检查配置。",
|
||
},
|
||
status=404,
|
||
)
|
||
|
||
result = None
|
||
audit_log = None
|
||
documents = UploadedDocument.objects.filter(
|
||
scenario_id=scenario["id"],
|
||
status=UploadedDocument.STATUS_INDEXED,
|
||
)
|
||
form = ChatForm(request.POST or None, documents=documents)
|
||
if request.method == "POST" and form.is_valid():
|
||
message = form.cleaned_data["message"]
|
||
try:
|
||
# 只把必要的运行选项传给 Agent Core,避免在 View 中散落模型细节。
|
||
result = run_agent(
|
||
scenario,
|
||
message,
|
||
options={"document_ids": form.cleaned_data["document_ids"]},
|
||
)
|
||
except Exception as exc:
|
||
result = AgentResult(status="failed", error=str(exc), answer="")
|
||
audit_log = create_audit_log(scenario["id"], scenario["name"], message, result)
|
||
|
||
return render(
|
||
request,
|
||
"chat/index.html",
|
||
{
|
||
"scenario": scenario,
|
||
"form": form,
|
||
"documents": documents,
|
||
"document_count": documents.count(),
|
||
"result": result,
|
||
"audit_log": audit_log,
|
||
},
|
||
)
|