初始化

This commit is contained in:
gozeros committed 2026-09-07 18:24:55 +08:00
1 parent 34474bd5fc
commit b638b541d0
3008 files changed
+837699

No files matched your search

@@ -0,0 +1,3 @@
from deerflow.agents.canvas_agent.agent import make_canvas_agent
__all__ = ["make_canvas_agent"]
@@ -0,0 +1,80 @@
from __future__ import annotations
import logging
from langchain.agents import create_agent
from langchain_core.runnables import RunnableConfig
from deerflow.agents.canvas_agent.prompt import build_canvas_system_prompt
from deerflow.agents.canvas_agent.tools import update_artifact_tool
from deerflow.agents.middlewares.clarification_middleware import ClarificationMiddleware
from deerflow.agents.middlewares.dangling_tool_call_middleware import DanglingToolCallMiddleware
from deerflow.agents.middlewares.loop_detection_middleware import LoopDetectionMiddleware
from deerflow.agents.middlewares.title_middleware import TitleMiddleware
from deerflow.agents.middlewares.tool_error_handling_middleware import ToolErrorHandlingMiddleware
from deerflow.agents.thread_state import ThreadState
from deerflow.config.app_config import get_app_config
from deerflow.models import create_chat_model
from deerflow.tools.builtins import ask_clarification_tool
logger = logging.getLogger(__name__)
def _get_runtime_config(config: RunnableConfig) -> dict:
cfg = dict(config.get("configurable", {}) or {})
context = config.get("context", {}) or {}
if isinstance(context, dict):
cfg.update(context)
return cfg
def make_canvas_agent(config: RunnableConfig):
"""LangGraph graph factory for canvas mode; signature compatible with LangGraph Server."""
app_config = get_app_config()
cfg = _get_runtime_config(config)
requested_model = cfg.get("model_name") or cfg.get("model")
if requested_model and app_config.get_model_config(requested_model):
model_name = requested_model
else:
if requested_model:
logger.warning("Canvas agent: model '%s' not found; falling back to default.", requested_model)
model_name = app_config.models[0].name if app_config.models else None
if model_name is None:
raise ValueError("No chat models configured. Please add at least one model in config.yaml.")
thinking_enabled = cfg.get("thinking_enabled", False)
model_config = app_config.get_model_config(model_name)
if thinking_enabled and model_config and not model_config.supports_thinking:
thinking_enabled = False
canvas_artifact_title = cfg.get("canvas_artifact_title") or None
canvas_artifact_type = cfg.get("canvas_artifact_type") or None
system_prompt = build_canvas_system_prompt(
artifact_title=canvas_artifact_title,
artifact_type=canvas_artifact_type,
)
logger.info(
"Create CanvasAgent -> model_name: %s, thinking_enabled: %s, artifact_title: %s",
model_name,
thinking_enabled,
canvas_artifact_title,
)
middlewares = [
DanglingToolCallMiddleware(),
ToolErrorHandlingMiddleware(),
TitleMiddleware(app_config=app_config),
LoopDetectionMiddleware(),
ClarificationMiddleware(),
]
return create_agent(
model=create_chat_model(name=model_name, thinking_enabled=thinking_enabled, app_config=app_config),
tools=[update_artifact_tool, ask_clarification_tool],
middleware=middlewares,
system_prompt=system_prompt,
state_schema=ThreadState,
)
@@ -0,0 +1,100 @@
def build_canvas_system_prompt(
artifact_title: str | None = None,
artifact_type: str | None = None,
) -> str:
existing_artifact_block = ""
if artifact_title:
type_label = "代码" if artifact_type == "code" else "文档"
existing_artifact_block = f"""
<existing_artifact>
用户当前有一个{type_label}制品,标题为 "{artifact_title}"。
请继续编辑该制品——除非用户明确要求新建,否则不要创建新制品。
</existing_artifact>
"""
return f"""You are a Canvas AI assistant that helps users create and edit documents and code.
<canvas_behavior>
You work with an **artifact** — a document or code file shown in the canvas panel on the right.
ALWAYS call `update_artifact` to save your work. Never embed the artifact content in your chat response.
Rules:
- On every request that creates or changes the artifact, call `update_artifact` ONCE with the COMPLETE updated content.
- In your text reply, describe what you did in 1–2 sentences.
- If the user is only asking a question (no edit needed), answer in text — skip the tool call.
</canvas_behavior>
<clarification_system>
Before creating a brand-new artifact or performing a major rewrite, verify you have enough
information to do the job well. When key details are missing, call `ask_clarification` FIRST
— do NOT start generating the artifact and ask questions mid-way.
**MUST clarify when (no existing artifact or major rewrite requested):**
1. OUTPUT TYPE IS VAGUE
- "帮我做个主页" / "make a homepage" → ask: tech stack (plain HTML / React / Vue?),
design style, which sections to include
- "写个报告" / "write a report" → ask: topic, target audience, expected length,
required sections
- "写个脚本" / "write a script" → ask: programming language, what it should do
2. REQUIRED CONTENT IS MISSING
- User wants a personal profile page but hasn't provided their name / bio / links
- User wants a data table but hasn't provided the data or schema
3. AMBIGUOUS APPROACH WITH SIGNIFICANTLY DIFFERENT OUTCOMES
- "Design a chat system" → ask: client–server or peer-to-peer, persistence needed?
- "Write an intro" → ask: formal essay or casual blog post?
**DO NOT clarify for:**
- Simple edits to an existing artifact: "make it bold", "fix the typo", "shorten paragraph 2"
- Formatting / style tweaks: "add comments", "use camelCase", "format the code"
- Quick actions: expand / shorten / formalize / casualize / add_comments / fix_bugs / optimize_code
- Requests where intent is clear from context (e.g., user pastes content and says "translate this")
- Follow-up turns where enough context already exists in the conversation
**Format for clarification (use options when practical):**
ask_clarification(
question="你希望这个主页使用什么技术栈?",
clarification_type="missing_info",
options=[
{{"id": "html", "label": "纯 HTML / CSS / JS", "description": "无框架,最简单"}},
{{"id": "react", "label": "React", "description": "组件化,适合复杂交互"}},
{{"id": "vue", "label": "Vue", "description": "渐进式框架,上手容易"}},
],
allow_custom=True,
)
CRITICAL: clarification ALWAYS comes before generating the artifact. Never produce a partial
artifact and then ask for clarification in the same response.
</clarification_system>
<artifact_context>
The current artifact state is injected into your context. When editing, build on the existing content exactly.
When creating from scratch, produce a complete, high-quality artifact in one shot.
</artifact_context>
{existing_artifact_block}
<selection_rewrite>
When the user's message contains a <selection> block, you MUST:
1. Identify the exact selection in the current artifact content.
2. Rewrite ONLY that selection according to the user's instruction.
3. Keep the rest of the artifact exactly unchanged.
4. Call update_artifact with the complete artifact where the selection has been replaced.
Example: if the artifact is "A B C" and the selection is "B" with instruction "make it bold",
produce "A **B** C" — not a new document.
</selection_rewrite>
<quick_actions>
When the user triggers a quick action, apply it to the full artifact unless specific highlighted text is provided:
- expand: Add depth and detail while preserving structure
- shorten: Condense to the essential points
- formalize: Rewrite in professional, formal language
- casualize: Rewrite in friendly, conversational language
- add_comments: Add clear, helpful code comments
- add_logs: Add appropriate logging statements
- fix_bugs: Identify and fix all bugs in the code
- optimize_code: Improve performance and readability
</quick_actions>
"""
# Backward-compatible constant for callers that don't pass artifact context.
CANVAS_SYSTEM_PROMPT = build_canvas_system_prompt()
@@ -0,0 +1,65 @@
from __future__ import annotations
from typing import Annotated, Literal
from langchain.tools import InjectedToolCallId, ToolRuntime, tool
from langchain_core.messages import ToolMessage
from langgraph.types import Command
from langgraph.typing import ContextT
from deerflow.agents.thread_state import CanvasArtifact, CanvasArtifactCode, CanvasArtifactText, ThreadState
@tool("update_artifact", parse_docstring=True)
def update_artifact_tool(
runtime: ToolRuntime[ContextT, ThreadState],
tool_call_id: Annotated[str, InjectedToolCallId],
type: Literal["text", "code"],
title: str,
content: str,
language: str = "other",
) -> Command:
"""Create or update the canvas artifact. Always call this to persist your work.
Args:
type: Artifact type — "text" for markdown documents, "code" for source code.
title: Human-readable title of the artifact.
content: Full artifact content: markdown text or complete source code.
language: Programming language (for code type only, e.g. "python", "typescript"). Ignored for text.
"""
current: CanvasArtifact | None = (runtime.state or {}).get("artifact") if runtime.state else None
if current is not None:
existing_contents = list(current.get("contents", []))
new_index = current.get("currentIndex", len(existing_contents)) + 1
else:
existing_contents = []
new_index = 1
if type == "text":
new_entry: CanvasArtifactText | CanvasArtifactCode = CanvasArtifactText(
index=new_index,
type="text",
title=title,
fullMarkdown=content,
)
else:
new_entry = CanvasArtifactCode(
index=new_index,
type="code",
title=title,
language=language,
code=content,
)
updated: CanvasArtifact = {
"currentIndex": new_index,
"contents": existing_contents + [new_entry],
}
return Command(
update={
"artifact": updated,
"messages": [ToolMessage("Artifact updated.", tool_call_id=tool_call_id)],
}
)