代码提交
This commit is contained in:
1 parent
b81f64a253
commit
050b1ad78e
45 files changed
+5011
-2694
No files matched your search
@@ -6,7 +6,8 @@
|
||||
],
|
||||
"env": ".env",
|
||||
"graphs": {
|
||||
"lead_agent": "deerflow.agents:make_lead_agent"
|
||||
"lead_agent": "deerflow.agents:make_lead_agent",
|
||||
"canvas_agent": "deerflow.agents.canvas_agent:make_canvas_agent"
|
||||
},
|
||||
"auth": {
|
||||
"path": "./app/gateway/langgraph_auth.py:auth"
|
||||
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
from deerflow.agents.canvas_agent.agent import make_canvas_agent
|
||||
|
||||
__all__ = ["make_canvas_agent"]
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
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 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
|
||||
|
||||
logger.info("Create CanvasAgent -> model_name: %s, thinking_enabled: %s", model_name, thinking_enabled)
|
||||
|
||||
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=CANVAS_SYSTEM_PROMPT,
|
||||
state_schema=ThreadState,
|
||||
)
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
CANVAS_SYSTEM_PROMPT = """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>
|
||||
|
||||
<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>
|
||||
|
||||
<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>
|
||||
"""
|
||||
+65
@@ -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)],
|
||||
}
|
||||
)
|
||||
@@ -1,4 +1,4 @@
|
||||
from typing import Annotated, NotRequired, TypedDict
|
||||
from typing import Annotated, Literal, NotRequired, Optional, TypedDict
|
||||
|
||||
from langchain.agents import AgentState
|
||||
|
||||
@@ -18,6 +18,26 @@ class ViewedImageData(TypedDict):
|
||||
mime_type: str
|
||||
|
||||
|
||||
class CanvasArtifactText(TypedDict):
|
||||
index: int
|
||||
type: Literal["text"]
|
||||
title: str
|
||||
fullMarkdown: str
|
||||
|
||||
|
||||
class CanvasArtifactCode(TypedDict):
|
||||
index: int
|
||||
type: Literal["code"]
|
||||
title: str
|
||||
language: str
|
||||
code: str
|
||||
|
||||
|
||||
class CanvasArtifact(TypedDict):
|
||||
currentIndex: int
|
||||
contents: list[CanvasArtifactText | CanvasArtifactCode]
|
||||
|
||||
|
||||
def merge_artifacts(existing: list[str] | None, new: list[str] | None) -> list[str]:
|
||||
"""Reducer for artifacts list - merges and deduplicates artifacts."""
|
||||
if existing is None:
|
||||
@@ -53,3 +73,11 @@ class ThreadState(AgentState):
|
||||
todos: NotRequired[list | None]
|
||||
uploaded_files: NotRequired[list[dict] | None]
|
||||
viewed_images: Annotated[dict[str, ViewedImageData], merge_viewed_images] # image_path -> {base64, mime_type}
|
||||
# Canvas fields (coexist with artifacts: list[str] which tracks file outputs)
|
||||
artifact: NotRequired[Optional[CanvasArtifact]]
|
||||
highlighted_text: NotRequired[Optional[str]]
|
||||
highlighted_code: NotRequired[Optional[str]]
|
||||
canvas_mode: NotRequired[Optional[Literal["text", "code"]]]
|
||||
quick_action_id: NotRequired[Optional[str]]
|
||||
web_search_enabled: NotRequired[bool]
|
||||
web_search_results: NotRequired[Optional[list[dict]]]
|
||||
Generated
+2692
-2692
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user