b24e985f82
Первый шаг графовой архитектуры из GRAPH_ARCHITECTURE.md. Заменили
«один активный промпт на всё» на «свой промпт на каждую ветку +
роутер выбирает ветку на каждой реплике».
Данные:
- Новая таблица intents (code, name, description, is_enabled,
order_index). Коды с префиксом `_` — системные (не responder).
- В agent_configs добавлен intent_id (nullable, FK SET NULL); убрана
глобальная уникальность version, вместо неё UniqueConstraint
(intent_id, version) — у каждой ветки свой счётчик версий.
- В messages добавлен intent_id (nullable, FK) — фиксируем, какую
ветку выбрал роутер для каждой реплики.
- Миграция cd0a88ef9080 в batch-режиме (SQLite не умеет ALTER для
constraints напрямую).
Сид:
- Стартовые 7 веток: new_booking, reschedule, price_question,
medical_question, general_info, escalate_human + `_router` как
системная ветка для промпта классификатора.
- Для каждой ветки — свой v1-промпт из prompts/intents/{code}.md.
- migrate_legacy_config_to_general_info: старый v1 из Спринта 3
(без intent_id) переносится на general_info с сохранением версии.
- ensure_seed_intents досиживает недостающие коды, существующие не
трогает — безопасно при добавлении новых веток.
Оркестрация и роутер:
- services/router_client.RouterClient — отдельный класс от LLMClient
(под будущую смену модели на более дешёвую). Метод classify(session,
history, text) возвращает {code, version}. Промпт классификатора
подтягивается из активного конфига ветки `_router`, fallback —
prompts/intents/_router.md. При сомнении/ошибке возвращает
general_info.
- services/chat_service.send_message теперь идёт через router.classify
→ берёт активный конфиг выбранной ветки → llm.chat. В сообщения
пишется intent_id, в треде фиксируется начальный agent_config_id.
В ответе — intent_code, intent_name, config_version, router_version.
API:
- GET /intents, GET /intents/{code}, PATCH /intents/{code} —
список веток со счётчиком версий, получение и переключение
is_enabled.
- /configs теперь требует intent_code как Query-параметр
(GET /configs, GET /configs/active) — выборка версий в рамках
ветки. POST /configs принимает intent_id.
- get_thread_detail JOIN-ит Intent — каждая реплика возвращает
intent_code + intent_name.
UI:
- settings.html переработан в 3-колоночный макет: слева список веток
с подгруппой «Системные» для `_router` (пометка «система» вместо
свитча), в центре редактор промпта/правил активной версии выбранной
ветки, справа список версий с активировать/удалить/загрузить.
Каждая ветка редактируется независимо — своя история версий,
своя активная.
- sandbox.html: у каждой реплики бейдж с intent_code, в отладке новый
блок «Решение роутера» (подсвеченный зелёным) с названием ветки,
версией её активного конфига и версией промпта роутера. Старый
«активная: v1» индикатор убран — он больше не имеет смысла (активная
у каждой ветки своя).
E2E проверено: разные реплики уходят в корректные ветки, каждая
отвечает по своему узкому промпту, промпт роутера редактируется в UI
как v2/v3 и откатывается — классификация сразу использует новую
версию.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
170 lines
3.3 KiB
Python
170 lines
3.3 KiB
Python
from pydantic import BaseModel, Field
|
|
|
|
|
|
class DocumentInfo(BaseModel):
|
|
document_id: str
|
|
name: str
|
|
chunks_count: int
|
|
file_type: str
|
|
created_at: str
|
|
metadata: dict = Field(default_factory=dict)
|
|
|
|
|
|
class ChunkPreview(BaseModel):
|
|
index: int
|
|
section: str = ""
|
|
page_number: int = 0
|
|
text_preview: str = ""
|
|
char_length: int = 0
|
|
|
|
|
|
class DocumentUploadResponse(BaseModel):
|
|
document_id: str
|
|
name: str
|
|
chunks_count: int
|
|
status: str = "indexed"
|
|
created_at: str
|
|
chunks_preview: list[ChunkPreview] = Field(default_factory=list)
|
|
|
|
|
|
class DocumentListResponse(BaseModel):
|
|
documents: list[DocumentInfo]
|
|
total: int
|
|
|
|
|
|
class ChunkDetail(BaseModel):
|
|
index: int
|
|
section: str = ""
|
|
page_number: int = 0
|
|
text: str = ""
|
|
char_length: int = 0
|
|
embedding: list[float] = Field(default_factory=list)
|
|
embedding_dim: int = 0
|
|
|
|
|
|
class DocumentChunksResponse(BaseModel):
|
|
document_id: str
|
|
name: str
|
|
file_type: str
|
|
chunks_count: int
|
|
chunks: list[ChunkDetail] = Field(default_factory=list)
|
|
|
|
|
|
class DocumentDeleteResponse(BaseModel):
|
|
ok: bool = True
|
|
deleted_chunks: int
|
|
|
|
|
|
class SourceInfo(BaseModel):
|
|
document_id: str
|
|
document_name: str
|
|
chunk_text: str
|
|
section: str = ""
|
|
page: int = 0
|
|
relevance_score: float = 0.0
|
|
|
|
|
|
class QueryResponse(BaseModel):
|
|
answer: str
|
|
sources: list[SourceInfo]
|
|
model_used: str
|
|
assembled_prompt: str = ""
|
|
|
|
|
|
class HealthResponse(BaseModel):
|
|
status: str = "ok"
|
|
chromadb: str
|
|
embedding_model: str
|
|
documents_count: int
|
|
chunks_count: int
|
|
|
|
|
|
class MessageInfo(BaseModel):
|
|
id: int
|
|
role: str
|
|
text: str
|
|
created_at: str
|
|
sources: list[SourceInfo] = Field(default_factory=list)
|
|
assembled_prompt: str = ""
|
|
intent_code: str = ""
|
|
intent_name: str = ""
|
|
|
|
|
|
class ThreadInfo(BaseModel):
|
|
id: int
|
|
name: str
|
|
created_at: str
|
|
updated_at: str
|
|
messages_count: int
|
|
first_message_preview: str = ""
|
|
|
|
|
|
class ThreadListResponse(BaseModel):
|
|
threads: list[ThreadInfo]
|
|
total: int
|
|
|
|
|
|
class ThreadDetailResponse(BaseModel):
|
|
id: int
|
|
name: str
|
|
created_at: str
|
|
updated_at: str
|
|
messages: list[MessageInfo] = Field(default_factory=list)
|
|
|
|
|
|
class ChatResponse(BaseModel):
|
|
thread_id: int
|
|
thread_name: str
|
|
message_id: int
|
|
intent_code: str = ""
|
|
intent_name: str = ""
|
|
config_version: int = 0
|
|
router_version: int | None = None
|
|
answer: str
|
|
sources: list[SourceInfo]
|
|
model_used: str
|
|
assembled_prompt: str = ""
|
|
|
|
|
|
class ThreadDeleteResponse(BaseModel):
|
|
ok: bool = True
|
|
deleted_messages: int
|
|
|
|
|
|
class AgentConfigInfo(BaseModel):
|
|
id: int
|
|
intent_id: int | None = None
|
|
intent_code: str = ""
|
|
intent_name: str = ""
|
|
version: int
|
|
name: str | None = None
|
|
system_prompt: str
|
|
rules_text: str = ""
|
|
is_active: bool
|
|
created_at: str
|
|
|
|
|
|
class AgentConfigListResponse(BaseModel):
|
|
configs: list[AgentConfigInfo]
|
|
total: int
|
|
|
|
|
|
class AgentConfigDeleteResponse(BaseModel):
|
|
ok: bool = True
|
|
|
|
|
|
class IntentInfo(BaseModel):
|
|
id: int
|
|
code: str
|
|
name: str
|
|
description: str = ""
|
|
is_enabled: bool
|
|
order_index: int
|
|
active_config_id: int | None = None
|
|
active_config_version: int | None = None
|
|
|
|
|
|
class IntentListResponse(BaseModel):
|
|
intents: list[IntentInfo]
|
|
total: int
|