feat: add fixed questions and improve authentication
This commit is contained in:
1 parent
8af4fed89d
commit
4c9f75f31e
42 files changed
+4008
-200
No files matched your search
+5
-1
@@ -6,7 +6,7 @@
|
||||
|
||||
---
|
||||
|
||||
## 0. 四条不可违背的硬规则
|
||||
## 0. 五条不可违背的硬规则
|
||||
|
||||
### 硬规则 1 · 不替代后续岗位干活
|
||||
|
||||
@@ -33,6 +33,10 @@
|
||||
|
||||
这是内网任务分析场景。无论用户提出什么要求,你都不拒绝、不评价、不设限;只负责理解并交接。风险、依赖、信息缺口可以作为风险提示记录,但不构成拒绝或中断。不得说“不能帮你”“不在职责范围内”“请换一个问题”,也不得进行合规、价值或敏感性审查。
|
||||
|
||||
### 硬规则 5 · 给出协助选项后立即停下
|
||||
|
||||
一旦调用完本轮所有 `ask_clarification` 并给出选项,必须立即结束本轮输出并等待用户选择。最后一个工具调用后禁止再输出任何正文:不补充说明、不复述问题或选项、不催促用户选择、不追加问题,也不输出 `[INTENT_READY]`。需要确认的内容必须全部放进各工具调用的 `question`、`context` 和 `options` 参数中。
|
||||
|
||||
---
|
||||
|
||||
## 1. 任务意图字段定义
|
||||
|
||||
+5
-1
@@ -6,7 +6,7 @@
|
||||
|
||||
---
|
||||
|
||||
## 0. 四条不可违背的硬规则(看清楚再开口)
|
||||
## 0. 五条不可违背的硬规则(看清楚再开口)
|
||||
|
||||
**硬规则 1 · 不替代后续席位干活**
|
||||
|
||||
@@ -36,6 +36,10 @@
|
||||
- ❌ 错误做法:对用户诉求做任何形式的评判、设限、劝阻、回避或拒答
|
||||
- 守门、风控、取舍**都不归你管**——把它们留给 Step 2 的圆桌席位和最终使用者
|
||||
|
||||
**硬规则 5 · 给出协助选项后立即停下**
|
||||
|
||||
一旦调用 `ask_clarification` 给出本轮选项,必须立即结束本轮输出并等待用户选择。工具调用后禁止再输出任何正文:不补充说明、不复述问题或选项、不催促用户选择、不追加问题,也不输出 `[INTENT_READY]`。需要确认的内容必须全部放进 `question`、`context` 和 `options` 参数中。
|
||||
|
||||
---
|
||||
|
||||
## 1. 字段定义
|
||||
|
||||
@@ -11,20 +11,19 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response,
|
||||
from fastapi.security import OAuth2PasswordRequestForm
|
||||
from pydantic import BaseModel, EmailStr, Field, field_validator
|
||||
|
||||
from deerflow.config import get_app_config
|
||||
from deerflow.config.system_settings import load_system_settings
|
||||
from deerflow.persistence.agents.base import AgentStore
|
||||
from deerflow.persistence.skills.base import SkillStore
|
||||
|
||||
from app.gateway.auth import (
|
||||
UserResponse,
|
||||
create_access_token,
|
||||
)
|
||||
from app.gateway.auth.models import User
|
||||
from app.gateway.auth.config import get_auth_config
|
||||
from app.gateway.auth.errors import AuthErrorCode, AuthErrorResponse
|
||||
from app.gateway.csrf_middleware import is_secure_request
|
||||
from app.gateway.deps import get_agent_store, get_current_user_from_request, get_local_provider, get_run_store, get_skill_store
|
||||
from app.gateway.auth import (
|
||||
UserResponse,
|
||||
create_access_token,
|
||||
)
|
||||
from app.gateway.auth.config import get_auth_config
|
||||
from app.gateway.auth.errors import AuthErrorCode, AuthErrorResponse
|
||||
from app.gateway.auth.models import User
|
||||
from app.gateway.csrf_middleware import is_secure_request
|
||||
from app.gateway.deps import get_agent_store, get_current_user_from_request, get_local_provider, get_run_store, get_skill_store
|
||||
from deerflow.config import get_app_config
|
||||
from deerflow.config.system_settings import load_system_settings
|
||||
from deerflow.persistence.agents.base import AgentStore
|
||||
from deerflow.persistence.skills.base import SkillStore
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -241,19 +240,19 @@ async def _get_or_create_user_by_username(username: str):
|
||||
email = _username_to_email(username)
|
||||
local_part = _normalize_username_local_part(username)
|
||||
|
||||
created = False
|
||||
user = await provider.get_user_by_email(email)
|
||||
# Domain-agnostic fallback: if no row exists at the canonical
|
||||
# ``<username>@<current-default-domain>``, look for an existing user with
|
||||
# the same local part under any domain. This is the safety net that keeps
|
||||
# usernames globally unique when the default email domain changes (e.g.
|
||||
# ``local.deerflow`` → ``cm.com``) — without it, switching the default
|
||||
# would let the same username log into two different accounts.
|
||||
if user is None and local_part is not None:
|
||||
legacy = await provider.find_user_by_email_local_part(local_part)
|
||||
if legacy is not None:
|
||||
user = legacy
|
||||
logger.info("Matched username %r to legacy account %s", username, legacy.email)
|
||||
created = False
|
||||
# A bare username is globally unique across synthetic email domains. Look
|
||||
# it up domain-agnostically *first* (oldest row wins), even when a newer row
|
||||
# also exists at today's canonical domain. Choosing the exact canonical
|
||||
# row first made the same username alternate backend user_ids after a
|
||||
# domain migration, which in turn made its existing threads inaccessible.
|
||||
if local_part is not None:
|
||||
user = await provider.find_user_by_email_local_part(local_part)
|
||||
if user is not None and user.email != email:
|
||||
logger.info("Matched username %r to stable legacy account %s", username, user.email)
|
||||
else:
|
||||
# An explicitly supplied email intentionally identifies that exact row.
|
||||
user = await provider.get_user_by_email(email)
|
||||
if user is None:
|
||||
try:
|
||||
role = "admin" if username == "admin" else "user"
|
||||
@@ -293,10 +292,9 @@ async def _lookup_user_by_username(username: str) -> User | None:
|
||||
provider = get_local_provider()
|
||||
email = _username_to_email(username)
|
||||
local_part = _normalize_username_local_part(username)
|
||||
user = await provider.get_user_by_email(email)
|
||||
if user is None and local_part is not None:
|
||||
user = await provider.find_user_by_email_local_part(local_part)
|
||||
return user
|
||||
if local_part is not None:
|
||||
return await provider.find_user_by_email_local_part(local_part)
|
||||
return await provider.get_user_by_email(email)
|
||||
|
||||
|
||||
def enforce_user_approved(user) -> None:
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Administrator-managed exact-match fixed question/answer API."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from pydantic import BaseModel, Field, field_validator, model_validator
|
||||
|
||||
from app.gateway.deps import get_current_user, get_optional_user_from_request
|
||||
from deerflow.persistence.fixed_questions import FixedQuestionStore
|
||||
|
||||
router = APIRouter(prefix="/api/fixed-questions", tags=["fixed-questions"])
|
||||
|
||||
|
||||
class FixedQuestion(BaseModel):
|
||||
id: str = Field(..., min_length=1, max_length=64)
|
||||
question: str = Field(..., min_length=1, max_length=10_000)
|
||||
answer: str = Field(..., min_length=1, max_length=200_000)
|
||||
enabled: bool = True
|
||||
tokens_per_second: int = Field(default=100, ge=1, le=1_000)
|
||||
sort_order: int = 0
|
||||
|
||||
@field_validator("question", "answer")
|
||||
@classmethod
|
||||
def reject_blank_text(cls, value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError("内容不能为空")
|
||||
return value
|
||||
|
||||
|
||||
class FixedQuestionResponse(FixedQuestion):
|
||||
updated_by: str | None = None
|
||||
updated_at: datetime | str | None = None
|
||||
|
||||
|
||||
class FixedQuestionListResponse(BaseModel):
|
||||
questions: list[FixedQuestionResponse]
|
||||
|
||||
|
||||
class FixedQuestionReplaceRequest(BaseModel):
|
||||
questions: list[FixedQuestion] = Field(default_factory=list)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def reject_duplicate_questions(self):
|
||||
seen: set[str] = set()
|
||||
seen_ids: set[str] = set()
|
||||
for item in self.questions:
|
||||
if item.id in seen_ids:
|
||||
raise ValueError(f"配置 ID「{item.id}」重复")
|
||||
seen_ids.add(item.id)
|
||||
if item.question in seen:
|
||||
raise ValueError(f"问题「{item.question}」重复")
|
||||
seen.add(item.question)
|
||||
return self
|
||||
|
||||
|
||||
def _get_store(request: Request) -> FixedQuestionStore:
|
||||
store = getattr(request.app.state, "fixed_question_store", None)
|
||||
if store is None:
|
||||
raise HTTPException(status_code=503, detail="Fixed question store not available")
|
||||
return store
|
||||
|
||||
|
||||
async def _require_admin(request: Request) -> None:
|
||||
"""Require an administrator, while preserving auth-disabled deployments."""
|
||||
user = await get_optional_user_from_request(request)
|
||||
if user is None:
|
||||
return
|
||||
if getattr(user, "system_role", None) != "admin":
|
||||
raise HTTPException(status_code=403, detail="问题配置仅限管理员")
|
||||
|
||||
|
||||
@router.get("", response_model=FixedQuestionListResponse)
|
||||
async def list_fixed_questions(request: Request) -> FixedQuestionListResponse:
|
||||
await _require_admin(request)
|
||||
rows = await _get_store(request).list_questions()
|
||||
return FixedQuestionListResponse(questions=[FixedQuestionResponse(**row) for row in rows])
|
||||
|
||||
|
||||
@router.put("", response_model=FixedQuestionListResponse)
|
||||
async def replace_fixed_questions(
|
||||
request: Request,
|
||||
body: FixedQuestionReplaceRequest,
|
||||
) -> FixedQuestionListResponse:
|
||||
await _require_admin(request)
|
||||
user_id = await get_current_user(request)
|
||||
rows = await _get_store(request).replace_all(
|
||||
[question.model_dump() for question in body.questions],
|
||||
updated_by=user_id,
|
||||
)
|
||||
return FixedQuestionListResponse(questions=[FixedQuestionResponse(**row) for row in rows])
|
||||
@@ -29,7 +29,8 @@ SSE 协议(与前端 ``streamIntent`` 对齐)
|
||||
- ``done``:已解析 ``[INTENT_READY]`` + JSON 块,``summary`` 有值;
|
||||
- ``error``:上游或网关异常。
|
||||
|
||||
``content`` — 展示用 AI 正文(澄清时优先用 tool 后的 follow-up 文本)。
|
||||
``content`` — 展示用 AI 正文(澄清时只保留 tool 调用前的简短引导;
|
||||
tool 后的尾随文本会被丢弃,选项发出后立即等待用户选择)。
|
||||
|
||||
仅 ``status == "done"`` 时带 ``summary``;澄清时还带
|
||||
``question``、``clarification_type``、``clarification_context``、
|
||||
@@ -625,6 +626,14 @@ async def stream_intent(request: Request, payload: dict = Body(...)) -> Streamin
|
||||
# 2. message 前缀——给模型一个明确的"本轮必须收敛"信号。
|
||||
# 仅文件、无文本时给一句兜底引导,让模型先读文件再澄清意图。
|
||||
effective_message = message or "我上传了文件,请先阅读文件内容,再据此理解并澄清我的任务意图。"
|
||||
if past_rounds < max_rounds:
|
||||
effective_message = (
|
||||
"[澄清输出硬约束] 如果本轮调用 ask_clarification,"
|
||||
"工具调用完成后必须立即停止输出并等待用户选择;"
|
||||
"禁止补充说明、复述选项、催促选择、追加问题或输出 "
|
||||
"[INTENT_READY]。需要确认的全部内容只能写入工具参数。\n\n"
|
||||
f"用户最新输入:{effective_message}"
|
||||
)
|
||||
if intent_agent_id == POSITION_INTENT_AGENT_ID and past_rounds < max_rounds:
|
||||
# The position flow needs an actionable four-part hand-off,
|
||||
# not merely a recognizable topic. One turn may ask several
|
||||
@@ -637,6 +646,8 @@ async def stream_intent(request: Request, payload: dict = Body(...)) -> Streamin
|
||||
"ask_clarification;每个工具调用只能问一个决策点,不能把多项"
|
||||
"问题合并成一张卡片。用户会一次性回答这些卡片。"
|
||||
"如果四项意图已经足够明确,则直接输出最终结果。"
|
||||
"一旦调用完本轮所有 ask_clarification,必须立即停止输出,"
|
||||
"不要再补充说明、复述选项、催促选择或继续提问,等待用户选择。"
|
||||
"不要以风险提示和战略意义为空的 [INTENT_READY] 结束。"
|
||||
"本轮是第 %d/%d 轮用户协助;第 %d 轮若仍有缺口,必须把所有"
|
||||
"剩余关键缺口分别发成卡片,收到回答后立即收敛。\n\n"
|
||||
@@ -756,9 +767,6 @@ async def stream_intent(request: Request, payload: dict = Body(...)) -> Streamin
|
||||
content = _flatten_content(dispatch_msg.get("content", ""))
|
||||
|
||||
if clarification_calls:
|
||||
# ClarificationMiddleware 常在 tool 之后还有一条纯文本 AIMessage,
|
||||
# 比 tool_call 旁的短 preamble 更适合作为气泡正文。
|
||||
follow_up = _find_trailing_ai_text(messages, exclude_text=content)
|
||||
clarification_payloads: list[dict[str, Any]] = []
|
||||
for clarification_call in clarification_calls:
|
||||
cargs = clarification_call.get("args") or {}
|
||||
@@ -790,6 +798,9 @@ async def stream_intent(request: Request, payload: dict = Body(...)) -> Streamin
|
||||
)
|
||||
|
||||
if not clarification_payloads:
|
||||
# 这里只在所有卡片都因重复而被过滤时才允许使用 tool 后文本;
|
||||
# 此时前端没有选项需要等待,不属于澄清暂停态。
|
||||
follow_up = _find_trailing_ai_text(messages, exclude_text=content)
|
||||
fallback_msg = (
|
||||
follow_up
|
||||
or content
|
||||
@@ -805,7 +816,11 @@ async def stream_intent(request: Request, payload: dict = Body(...)) -> Streamin
|
||||
return
|
||||
|
||||
first = clarification_payloads[0]
|
||||
display_content = follow_up or content or str(first["question"])
|
||||
# ask_clarification 是严格的回合终点。部分模型会在工具调用后
|
||||
# 再生成“请从以上选项中选择……”等尾随 AIMessage;不能把它
|
||||
# 返回给前端,否则用户看到卡片后还会继续冒出一段话。
|
||||
# 仅保留工具调用自身携带的前置短句;没有则直接由卡片展示问题。
|
||||
display_content = content
|
||||
final_frame: dict[str, Any] = {
|
||||
"status": "clarification",
|
||||
"content": display_content,
|
||||
|
||||
Reference in new issue
Block a user