2026-03-06 22:39:58 +08:00
|
|
|
import json
|
|
|
|
|
import logging
|
|
|
|
|
|
|
|
|
|
from fastapi import APIRouter
|
|
|
|
|
from pydantic import BaseModel, Field
|
|
|
|
|
|
refactor: split backend into harness (deerflow.*) and app (app.*) (#1131)
* refactor: extract shared utils to break harness→app cross-layer imports
Move _validate_skill_frontmatter to src/skills/validation.py and
CONVERTIBLE_EXTENSIONS + convert_file_to_markdown to src/utils/file_conversion.py.
This eliminates the two reverse dependencies from client.py (harness layer)
into gateway/routers/ (app layer), preparing for the harness/app package split.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: split backend/src into harness (deerflow.*) and app (app.*)
Physically split the monolithic backend/src/ package into two layers:
- **Harness** (`packages/harness/deerflow/`): publishable agent framework
package with import prefix `deerflow.*`. Contains agents, sandbox, tools,
models, MCP, skills, config, and all core infrastructure.
- **App** (`app/`): unpublished application code with import prefix `app.*`.
Contains gateway (FastAPI REST API) and channels (IM integrations).
Key changes:
- Move 13 harness modules to packages/harness/deerflow/ via git mv
- Move gateway + channels to app/ via git mv
- Rename all imports: src.* → deerflow.* (harness) / app.* (app layer)
- Set up uv workspace with deerflow-harness as workspace member
- Update langgraph.json, config.example.yaml, all scripts, Docker files
- Add build-system (hatchling) to harness pyproject.toml
- Add PYTHONPATH=. to gateway startup commands for app.* resolution
- Update ruff.toml with known-first-party for import sorting
- Update all documentation to reflect new directory structure
Boundary rule enforced: harness code never imports from app.
All 429 tests pass. Lint clean.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add harness→app boundary check test and update docs
Add test_harness_boundary.py that scans all Python files in
packages/harness/deerflow/ and fails if any `from app.*` or
`import app.*` statement is found. This enforces the architectural
rule that the harness layer never depends on the app layer.
Update CLAUDE.md to document the harness/app split architecture,
import conventions, and the boundary enforcement test.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: add config versioning with auto-upgrade on startup
When config.example.yaml schema changes, developers' local config.yaml
files can silently become outdated. This adds a config_version field and
auto-upgrade mechanism so breaking changes (like src.* → deerflow.*
renames) are applied automatically before services start.
- Add config_version: 1 to config.example.yaml
- Add startup version check warning in AppConfig.from_file()
- Add scripts/config-upgrade.sh with migration registry for value replacements
- Add `make config-upgrade` target
- Auto-run config-upgrade in serve.sh and start-daemon.sh before starting services
- Add config error hints in service failure messages
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix comments
* fix: update src.* import in test_sandbox_tools_security to deerflow.*
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: handle empty config and search parent dirs for config.example.yaml
Address Copilot review comments on PR #1131:
- Guard against yaml.safe_load() returning None for empty config files
- Search parent directories for config.example.yaml instead of only
looking next to config.yaml, fixing detection in common setups
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: correct skills root path depth and config_version type coercion
- loader.py: fix get_skills_root_path() to use 5 parent levels (was 3)
after harness split, file lives at packages/harness/deerflow/skills/
so parent×3 resolved to backend/packages/harness/ instead of backend/
- app_config.py: coerce config_version to int() before comparison in
_check_config_version() to prevent TypeError when YAML stores value
as string (e.g. config_version: "1")
- tests: add regression tests for both fixes
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix: update test imports from src.* to deerflow.*/app.* after harness refactor
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-14 22:55:52 +08:00
|
|
|
from deerflow.models import create_chat_model
|
2026-03-06 22:39:58 +08:00
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
router = APIRouter(prefix="/api", tags=["suggestions"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class SuggestionMessage(BaseModel):
|
|
|
|
|
role: str = Field(..., description="Message role: user|assistant")
|
|
|
|
|
content: str = Field(..., description="Message content as plain text")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class SuggestionsRequest(BaseModel):
|
|
|
|
|
messages: list[SuggestionMessage] = Field(..., description="Recent conversation messages")
|
|
|
|
|
n: int = Field(default=3, ge=1, le=5, description="Number of suggestions to generate")
|
|
|
|
|
model_name: str | None = Field(default=None, description="Optional model override")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class SuggestionsResponse(BaseModel):
|
|
|
|
|
suggestions: list[str] = Field(default_factory=list, description="Suggested follow-up questions")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _strip_markdown_code_fence(text: str) -> str:
|
|
|
|
|
stripped = text.strip()
|
|
|
|
|
if not stripped.startswith("```"):
|
|
|
|
|
return stripped
|
|
|
|
|
lines = stripped.splitlines()
|
|
|
|
|
if len(lines) >= 3 and lines[0].startswith("```") and lines[-1].startswith("```"):
|
|
|
|
|
return "\n".join(lines[1:-1]).strip()
|
|
|
|
|
return stripped
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _parse_json_string_list(text: str) -> list[str] | None:
|
|
|
|
|
candidate = _strip_markdown_code_fence(text)
|
|
|
|
|
start = candidate.find("[")
|
|
|
|
|
end = candidate.rfind("]")
|
|
|
|
|
if start == -1 or end == -1 or end <= start:
|
|
|
|
|
return None
|
|
|
|
|
candidate = candidate[start : end + 1]
|
|
|
|
|
try:
|
|
|
|
|
data = json.loads(candidate)
|
|
|
|
|
except Exception:
|
|
|
|
|
return None
|
|
|
|
|
if not isinstance(data, list):
|
|
|
|
|
return None
|
|
|
|
|
out: list[str] = []
|
|
|
|
|
for item in data:
|
|
|
|
|
if not isinstance(item, str):
|
|
|
|
|
continue
|
|
|
|
|
s = item.strip()
|
|
|
|
|
if not s:
|
|
|
|
|
continue
|
|
|
|
|
out.append(s)
|
|
|
|
|
return out
|
|
|
|
|
|
|
|
|
|
|
2026-03-13 21:20:15 +08:00
|
|
|
def _extract_response_text(content: object) -> str:
|
|
|
|
|
if isinstance(content, str):
|
|
|
|
|
return content
|
|
|
|
|
if isinstance(content, list):
|
|
|
|
|
parts: list[str] = []
|
|
|
|
|
for block in content:
|
|
|
|
|
if isinstance(block, str):
|
|
|
|
|
parts.append(block)
|
|
|
|
|
elif isinstance(block, dict) and block.get("type") == "text":
|
|
|
|
|
text = block.get("text")
|
|
|
|
|
if isinstance(text, str):
|
|
|
|
|
parts.append(text)
|
|
|
|
|
return "\n".join(parts) if parts else ""
|
|
|
|
|
if content is None:
|
|
|
|
|
return ""
|
|
|
|
|
return str(content)
|
|
|
|
|
|
|
|
|
|
|
2026-03-06 22:39:58 +08:00
|
|
|
def _format_conversation(messages: list[SuggestionMessage]) -> str:
|
|
|
|
|
parts: list[str] = []
|
|
|
|
|
for m in messages:
|
|
|
|
|
role = m.role.strip().lower()
|
|
|
|
|
if role in ("user", "human"):
|
|
|
|
|
parts.append(f"User: {m.content.strip()}")
|
|
|
|
|
elif role in ("assistant", "ai"):
|
|
|
|
|
parts.append(f"Assistant: {m.content.strip()}")
|
|
|
|
|
else:
|
|
|
|
|
parts.append(f"{m.role}: {m.content.strip()}")
|
|
|
|
|
return "\n".join(parts).strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.post(
|
|
|
|
|
"/threads/{thread_id}/suggestions",
|
|
|
|
|
response_model=SuggestionsResponse,
|
|
|
|
|
summary="Generate Follow-up Questions",
|
|
|
|
|
description="Generate short follow-up questions a user might ask next, based on recent conversation context.",
|
|
|
|
|
)
|
|
|
|
|
async def generate_suggestions(thread_id: str, request: SuggestionsRequest) -> SuggestionsResponse:
|
|
|
|
|
if not request.messages:
|
|
|
|
|
return SuggestionsResponse(suggestions=[])
|
|
|
|
|
|
|
|
|
|
n = request.n
|
|
|
|
|
conversation = _format_conversation(request.messages)
|
|
|
|
|
if not conversation:
|
|
|
|
|
return SuggestionsResponse(suggestions=[])
|
|
|
|
|
|
|
|
|
|
prompt = (
|
|
|
|
|
"You are generating follow-up questions to help the user continue the conversation.\n"
|
|
|
|
|
f"Based on the conversation below, produce EXACTLY {n} short questions the user might ask next.\n"
|
|
|
|
|
"Requirements:\n"
|
|
|
|
|
"- Questions must be relevant to the conversation.\n"
|
|
|
|
|
"- Questions must be written in the same language as the user.\n"
|
|
|
|
|
"- Keep each question concise (ideally <= 20 words / <= 40 Chinese characters).\n"
|
|
|
|
|
"- Do NOT include numbering, markdown, or any extra text.\n"
|
|
|
|
|
"- Output MUST be a JSON array of strings only.\n\n"
|
|
|
|
|
"Conversation:\n"
|
|
|
|
|
f"{conversation}\n"
|
2026-03-10 11:24:53 +08:00
|
|
|
)
|
2026-03-06 22:39:58 +08:00
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
model = create_chat_model(name=request.model_name, thinking_enabled=False)
|
|
|
|
|
response = model.invoke(prompt)
|
2026-03-13 21:20:15 +08:00
|
|
|
raw = _extract_response_text(response.content)
|
2026-03-06 22:39:58 +08:00
|
|
|
suggestions = _parse_json_string_list(raw) or []
|
|
|
|
|
cleaned = [s.replace("\n", " ").strip() for s in suggestions if s.strip()]
|
|
|
|
|
cleaned = cleaned[:n]
|
|
|
|
|
return SuggestionsResponse(suggestions=cleaned)
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
logger.exception("Failed to generate suggestions: thread_id=%s err=%s", thread_id, exc)
|
|
|
|
|
return SuggestionsResponse(suggestions=[])
|