feat(chat): 打通场景对话与结果展示

This commit is contained in:
2026-05-30 00:10:47 +08:00
parent 5c9718ddb1
commit ba3f5fc584
7 changed files with 224 additions and 0 deletions

1
apps/chat/__init__.py Normal file
View File

@@ -0,0 +1 @@

6
apps/chat/apps.py Normal file
View File

@@ -0,0 +1,6 @@
from django.apps import AppConfig
class ChatConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "apps.chat"

30
apps/chat/forms.py Normal file
View File

@@ -0,0 +1,30 @@
from django import forms
class ChatForm(forms.Form):
message = forms.CharField(
label="问题",
max_length=4000,
error_messages={
"required": "请输入要咨询的问题。",
"max_length": "问题过长,请控制在 4000 字以内。",
},
widget=forms.Textarea(attrs={"rows": 6}),
)
document_ids = forms.MultipleChoiceField(
label="文档范围",
required=False,
choices=(),
widget=forms.CheckboxSelectMultiple,
error_messages={"invalid_choice": "请选择当前场景下已入库的文档。"},
)
def __init__(self, *args, documents=None, **kwargs):
super().__init__(*args, **kwargs)
documents = documents or []
self.fields["document_ids"].choices = [
(str(document.id), document.original_name) for document in documents
]
def clean_document_ids(self):
return [int(document_id) for document_id in self.cleaned_data.get("document_ids", [])]

10
apps/chat/urls.py Normal file
View File

@@ -0,0 +1,10 @@
from django.urls import path
from . import views
app_name = "chat"
urlpatterns = [
path("<str:scenario_id>/", views.index, name="index"),
]

56
apps/chat/views.py Normal file
View File

@@ -0,0 +1,56 @@
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):
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:
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,
"result": result,
"audit_log": audit_log,
},
)