fix: normalize structured LLM content in serialization and memory updater (#1215)
* fix: normalize ToolMessage structured content in serialization
When models return ToolMessage content as a list of content blocks
(e.g. [{"type": "text", "text": "..."}]), the UI previously displayed
the raw Python repr string instead of the extracted text.
Replace str(msg.content) with the existing _extract_text() helper in
both _serialize_message() and stream() to properly normalize
list-of-blocks content to plain text.
Fixes #1149
Also fixes the same root cause as #1188 (characters displayed one per
line when tool response content is returned as structured blocks).
Added 11 regression tests covering string, list-of-blocks, mixed,
empty, and fallback content types.
* fix(memory): extract text from structured LLM responses in memory updater
When LLMs return response content as list of content blocks
(e.g. [{"type": "text", "text": "..."}]) instead of plain strings,
str() produces Python repr which breaks JSON parsing in the memory
updater. This caused memory updates to silently fail.
Changes:
- Add _extract_text() helper in updater.py for safe content normalization
- Use _extract_text() instead of str(response.content) in update_memory()
- Fix format_conversation_for_update() to handle plain strings in list content
- Fix subagent executor fallback path to extract text from list content
- Replace print() with structured logging (logger.info/warning/error)
- Add 13 regression tests covering _extract_text, format_conversation,
and update_memory with structured LLM responses
* fix: address Copilot review - defensive text extraction + logger.exception
- client.py _extract_text: use block.get('text') + isinstance check (prevent KeyError/TypeError)
- prompt.py format_conversation_for_update: same defensive check for dict text blocks
- executor.py: type-safe text extraction in both code paths, fallback to placeholder instead of str(raw_content)
- updater.py: use logger.exception() instead of logger.error() for traceback preservation
* Apply suggestions from code review
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* fix: preserve chunked structured content without spurious newlines
* fix: restore backend unit test compatibility
---------
Co-authored-by: Exploreunive <Exploreunive@users.noreply.github.com>
Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-03-22 17:29:29 +08:00
|
|
|
from unittest.mock import MagicMock, patch
|
2026-03-18 22:41:13 +08:00
|
|
|
|
fix: normalize structured LLM content in serialization and memory updater (#1215)
* fix: normalize ToolMessage structured content in serialization
When models return ToolMessage content as a list of content blocks
(e.g. [{"type": "text", "text": "..."}]), the UI previously displayed
the raw Python repr string instead of the extracted text.
Replace str(msg.content) with the existing _extract_text() helper in
both _serialize_message() and stream() to properly normalize
list-of-blocks content to plain text.
Fixes #1149
Also fixes the same root cause as #1188 (characters displayed one per
line when tool response content is returned as structured blocks).
Added 11 regression tests covering string, list-of-blocks, mixed,
empty, and fallback content types.
* fix(memory): extract text from structured LLM responses in memory updater
When LLMs return response content as list of content blocks
(e.g. [{"type": "text", "text": "..."}]) instead of plain strings,
str() produces Python repr which breaks JSON parsing in the memory
updater. This caused memory updates to silently fail.
Changes:
- Add _extract_text() helper in updater.py for safe content normalization
- Use _extract_text() instead of str(response.content) in update_memory()
- Fix format_conversation_for_update() to handle plain strings in list content
- Fix subagent executor fallback path to extract text from list content
- Replace print() with structured logging (logger.info/warning/error)
- Add 13 regression tests covering _extract_text, format_conversation,
and update_memory with structured LLM responses
* fix: address Copilot review - defensive text extraction + logger.exception
- client.py _extract_text: use block.get('text') + isinstance check (prevent KeyError/TypeError)
- prompt.py format_conversation_for_update: same defensive check for dict text blocks
- executor.py: type-safe text extraction in both code paths, fallback to placeholder instead of str(raw_content)
- updater.py: use logger.exception() instead of logger.error() for traceback preservation
* Apply suggestions from code review
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* fix: preserve chunked structured content without spurious newlines
* fix: restore backend unit test compatibility
---------
Co-authored-by: Exploreunive <Exploreunive@users.noreply.github.com>
Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-03-22 17:29:29 +08:00
|
|
|
from deerflow.agents.memory.prompt import format_conversation_for_update
|
|
|
|
|
from deerflow.agents.memory.updater import MemoryUpdater, _extract_text
|
2026-03-18 22:41:13 +08:00
|
|
|
from deerflow.config.memory_config import MemoryConfig
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _make_memory(facts: list[dict[str, object]] | None = None) -> dict[str, object]:
|
|
|
|
|
return {
|
|
|
|
|
"version": "1.0",
|
|
|
|
|
"lastUpdated": "",
|
|
|
|
|
"user": {
|
|
|
|
|
"workContext": {"summary": "", "updatedAt": ""},
|
|
|
|
|
"personalContext": {"summary": "", "updatedAt": ""},
|
|
|
|
|
"topOfMind": {"summary": "", "updatedAt": ""},
|
|
|
|
|
},
|
|
|
|
|
"history": {
|
|
|
|
|
"recentMonths": {"summary": "", "updatedAt": ""},
|
|
|
|
|
"earlierContext": {"summary": "", "updatedAt": ""},
|
|
|
|
|
"longTermBackground": {"summary": "", "updatedAt": ""},
|
|
|
|
|
},
|
|
|
|
|
"facts": facts or [],
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _memory_config(**overrides: object) -> MemoryConfig:
|
|
|
|
|
config = MemoryConfig()
|
|
|
|
|
for key, value in overrides.items():
|
|
|
|
|
setattr(config, key, value)
|
|
|
|
|
return config
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_apply_updates_skips_existing_duplicate_and_preserves_removals() -> None:
|
|
|
|
|
updater = MemoryUpdater()
|
|
|
|
|
current_memory = _make_memory(
|
|
|
|
|
facts=[
|
|
|
|
|
{
|
|
|
|
|
"id": "fact_existing",
|
|
|
|
|
"content": "User likes Python",
|
|
|
|
|
"category": "preference",
|
|
|
|
|
"confidence": 0.9,
|
|
|
|
|
"createdAt": "2026-03-18T00:00:00Z",
|
|
|
|
|
"source": "thread-a",
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
"id": "fact_remove",
|
|
|
|
|
"content": "Old context to remove",
|
|
|
|
|
"category": "context",
|
|
|
|
|
"confidence": 0.8,
|
|
|
|
|
"createdAt": "2026-03-18T00:00:00Z",
|
|
|
|
|
"source": "thread-a",
|
|
|
|
|
},
|
|
|
|
|
]
|
|
|
|
|
)
|
|
|
|
|
update_data = {
|
|
|
|
|
"factsToRemove": ["fact_remove"],
|
|
|
|
|
"newFacts": [
|
|
|
|
|
{"content": "User likes Python", "category": "preference", "confidence": 0.95},
|
|
|
|
|
],
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
with patch(
|
|
|
|
|
"deerflow.agents.memory.updater.get_memory_config",
|
|
|
|
|
return_value=_memory_config(max_facts=100, fact_confidence_threshold=0.7),
|
|
|
|
|
):
|
|
|
|
|
result = updater._apply_updates(current_memory, update_data, thread_id="thread-b")
|
|
|
|
|
|
|
|
|
|
assert [fact["content"] for fact in result["facts"]] == ["User likes Python"]
|
|
|
|
|
assert all(fact["id"] != "fact_remove" for fact in result["facts"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_apply_updates_skips_same_batch_duplicates_and_keeps_source_metadata() -> None:
|
|
|
|
|
updater = MemoryUpdater()
|
|
|
|
|
current_memory = _make_memory()
|
|
|
|
|
update_data = {
|
|
|
|
|
"newFacts": [
|
|
|
|
|
{"content": "User prefers dark mode", "category": "preference", "confidence": 0.91},
|
|
|
|
|
{"content": "User prefers dark mode", "category": "preference", "confidence": 0.92},
|
|
|
|
|
{"content": "User works on DeerFlow", "category": "context", "confidence": 0.87},
|
|
|
|
|
],
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
with patch(
|
|
|
|
|
"deerflow.agents.memory.updater.get_memory_config",
|
|
|
|
|
return_value=_memory_config(max_facts=100, fact_confidence_threshold=0.7),
|
|
|
|
|
):
|
|
|
|
|
result = updater._apply_updates(current_memory, update_data, thread_id="thread-42")
|
|
|
|
|
|
|
|
|
|
assert [fact["content"] for fact in result["facts"]] == [
|
|
|
|
|
"User prefers dark mode",
|
|
|
|
|
"User works on DeerFlow",
|
|
|
|
|
]
|
|
|
|
|
assert all(fact["id"].startswith("fact_") for fact in result["facts"])
|
|
|
|
|
assert all(fact["source"] == "thread-42" for fact in result["facts"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_apply_updates_preserves_threshold_and_max_facts_trimming() -> None:
|
|
|
|
|
updater = MemoryUpdater()
|
|
|
|
|
current_memory = _make_memory(
|
|
|
|
|
facts=[
|
|
|
|
|
{
|
|
|
|
|
"id": "fact_python",
|
|
|
|
|
"content": "User likes Python",
|
|
|
|
|
"category": "preference",
|
|
|
|
|
"confidence": 0.95,
|
|
|
|
|
"createdAt": "2026-03-18T00:00:00Z",
|
|
|
|
|
"source": "thread-a",
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
"id": "fact_dark_mode",
|
|
|
|
|
"content": "User prefers dark mode",
|
|
|
|
|
"category": "preference",
|
|
|
|
|
"confidence": 0.8,
|
|
|
|
|
"createdAt": "2026-03-18T00:00:00Z",
|
|
|
|
|
"source": "thread-a",
|
|
|
|
|
},
|
|
|
|
|
]
|
|
|
|
|
)
|
|
|
|
|
update_data = {
|
|
|
|
|
"newFacts": [
|
|
|
|
|
{"content": "User prefers dark mode", "category": "preference", "confidence": 0.9},
|
|
|
|
|
{"content": "User uses uv", "category": "context", "confidence": 0.85},
|
|
|
|
|
{"content": "User likes noisy logs", "category": "behavior", "confidence": 0.6},
|
|
|
|
|
],
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
with patch(
|
|
|
|
|
"deerflow.agents.memory.updater.get_memory_config",
|
|
|
|
|
return_value=_memory_config(max_facts=2, fact_confidence_threshold=0.7),
|
|
|
|
|
):
|
|
|
|
|
result = updater._apply_updates(current_memory, update_data, thread_id="thread-9")
|
|
|
|
|
|
|
|
|
|
assert [fact["content"] for fact in result["facts"]] == [
|
|
|
|
|
"User likes Python",
|
|
|
|
|
"User uses uv",
|
|
|
|
|
]
|
|
|
|
|
assert all(fact["content"] != "User likes noisy logs" for fact in result["facts"])
|
|
|
|
|
assert result["facts"][1]["source"] == "thread-9"
|
fix: normalize structured LLM content in serialization and memory updater (#1215)
* fix: normalize ToolMessage structured content in serialization
When models return ToolMessage content as a list of content blocks
(e.g. [{"type": "text", "text": "..."}]), the UI previously displayed
the raw Python repr string instead of the extracted text.
Replace str(msg.content) with the existing _extract_text() helper in
both _serialize_message() and stream() to properly normalize
list-of-blocks content to plain text.
Fixes #1149
Also fixes the same root cause as #1188 (characters displayed one per
line when tool response content is returned as structured blocks).
Added 11 regression tests covering string, list-of-blocks, mixed,
empty, and fallback content types.
* fix(memory): extract text from structured LLM responses in memory updater
When LLMs return response content as list of content blocks
(e.g. [{"type": "text", "text": "..."}]) instead of plain strings,
str() produces Python repr which breaks JSON parsing in the memory
updater. This caused memory updates to silently fail.
Changes:
- Add _extract_text() helper in updater.py for safe content normalization
- Use _extract_text() instead of str(response.content) in update_memory()
- Fix format_conversation_for_update() to handle plain strings in list content
- Fix subagent executor fallback path to extract text from list content
- Replace print() with structured logging (logger.info/warning/error)
- Add 13 regression tests covering _extract_text, format_conversation,
and update_memory with structured LLM responses
* fix: address Copilot review - defensive text extraction + logger.exception
- client.py _extract_text: use block.get('text') + isinstance check (prevent KeyError/TypeError)
- prompt.py format_conversation_for_update: same defensive check for dict text blocks
- executor.py: type-safe text extraction in both code paths, fallback to placeholder instead of str(raw_content)
- updater.py: use logger.exception() instead of logger.error() for traceback preservation
* Apply suggestions from code review
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* fix: preserve chunked structured content without spurious newlines
* fix: restore backend unit test compatibility
---------
Co-authored-by: Exploreunive <Exploreunive@users.noreply.github.com>
Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-03-22 17:29:29 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
# _extract_text — LLM response content normalization
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class TestExtractText:
|
|
|
|
|
"""_extract_text should normalize all content shapes to plain text."""
|
|
|
|
|
|
|
|
|
|
def test_string_passthrough(self):
|
|
|
|
|
assert _extract_text("hello world") == "hello world"
|
|
|
|
|
|
|
|
|
|
def test_list_single_text_block(self):
|
|
|
|
|
assert _extract_text([{"type": "text", "text": "hello"}]) == "hello"
|
|
|
|
|
|
|
|
|
|
def test_list_multiple_text_blocks_joined(self):
|
|
|
|
|
content = [
|
|
|
|
|
{"type": "text", "text": "part one"},
|
|
|
|
|
{"type": "text", "text": "part two"},
|
|
|
|
|
]
|
|
|
|
|
assert _extract_text(content) == "part one\npart two"
|
|
|
|
|
|
|
|
|
|
def test_list_plain_strings(self):
|
|
|
|
|
assert _extract_text(["raw string"]) == "raw string"
|
|
|
|
|
|
|
|
|
|
def test_list_string_chunks_join_without_separator(self):
|
feat(harness): integration ACP agent tool (#1344)
* 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>
* feat(harness): add tool-first ACP agent invocation (#37)
* feat(harness): add tool-first ACP agent invocation
* build(harness): make ACP dependency required
* fix(harness): address ACP review feedback
* feat(harness): decouple ACP agent workspace from thread data
ACP agents (codex, claude-code) previously used per-thread workspace
directories, causing path resolution complexity and coupling task
execution to DeerFlow's internal thread data layout. This change:
- Replace _resolve_cwd() with a fixed _get_work_dir() that always uses
{base_dir}/acp-workspace/, eliminating virtual path translation and
thread_id lookups
- Introduce /mnt/acp-workspace virtual path for lead agent read-only
access to ACP agent output files (same pattern as /mnt/skills)
- Add security guards: read-only validation, path traversal prevention,
command path allowlisting, and output masking for acp-workspace
- Update system prompt and tool description to guide LLM: send
self-contained tasks to ACP agents, copy results via /mnt/acp-workspace
- Add 11 new security tests for ACP workspace path handling
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(prompt): inject ACP section only when ACP agents are configured
The ACP agent guidance in the system prompt is now conditionally built
by _build_acp_section(), which checks get_acp_agents() and returns an
empty string when no ACP agents are configured. This avoids polluting
the prompt with irrelevant instructions for users who don't use ACP.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix lint
* fix(harness): address Copilot review comments on sandbox path handling and ACP tool
- local_sandbox: fix path-segment boundary bug in _resolve_path (== or startswith +"/")
and add lookahead in _resolve_paths_in_command regex to prevent /mnt/skills matching
inside /mnt/skills-extra
- local_sandbox_provider: replace print() with logger.warning(..., exc_info=True)
- invoke_acp_agent_tool: guard getattr(option, "optionId") with None default + continue;
move full prompt from INFO to DEBUG level (truncated to 200 chars)
- sandbox/tools: fix _get_acp_workspace_host_path docstring to match implementation;
remove misleading "read-only" language from validate_local_bash_command_paths
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix(acp): thread-isolated workspaces, permission guardrail, and ContextVar registry
P1.1 – ACP workspace thread isolation
- Add `Paths.acp_workspace_dir(thread_id)` for per-thread paths
- `_get_work_dir(thread_id)` in invoke_acp_agent_tool now uses
`{base_dir}/threads/{thread_id}/acp-workspace/`; falls back to
global workspace when thread_id is absent or invalid
- `_invoke` extracts thread_id from `RunnableConfig` via
`Annotated[RunnableConfig, InjectedToolArg]`
- `sandbox/tools.py`: `_get_acp_workspace_host_path(thread_id)`,
`_resolve_acp_workspace_path(path, thread_id)`, and all callers
(`replace_virtual_paths_in_command`, `mask_local_paths_in_output`,
`ls_tool`, `read_file_tool`) now resolve ACP paths per-thread
P1.2 – ACP permission guardrail
- New `auto_approve_permissions: bool = False` field in `ACPAgentConfig`
- `_build_permission_response(options, *, auto_approve: bool)` now
defaults to deny; only approves when `auto_approve=True`
- Document field in `config.example.yaml`
P2 – Deferred tool registry race condition
- Replace module-level `_registry` global with `contextvars.ContextVar`
- Each asyncio request context gets its own registry; worker threads
inherit the context automatically via `loop.run_in_executor`
- Expose `get_deferred_registry` / `set_deferred_registry` /
`reset_deferred_registry` helpers
Tests: 831 pass (57 for affected modules, 3 new tests)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix(sandbox): mount /mnt/acp-workspace in docker sandbox container
The AioSandboxProvider was not mounting the ACP workspace into the
sandbox container, so /mnt/acp-workspace was inaccessible when the lead
agent tried to read ACP results in docker mode.
Changes:
- `ensure_thread_dirs`: also create `acp-workspace/` (chmod 0o777) so
the directory exists before the sandbox container starts — required
for Docker volume mounts
- `_get_thread_mounts`: add read-only `/mnt/acp-workspace` mount using
the per-thread host path (`host_paths.acp_workspace_dir(thread_id)`)
- Update stale CLAUDE.md description (was "fixed global workspace")
Tests: `test_aio_sandbox_provider.py` (4 new tests)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix(lint): remove unused imports in test_aio_sandbox_provider
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix config
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 14:20:18 +08:00
|
|
|
content = ['{"user"', ': "alice"}']
|
fix: normalize structured LLM content in serialization and memory updater (#1215)
* fix: normalize ToolMessage structured content in serialization
When models return ToolMessage content as a list of content blocks
(e.g. [{"type": "text", "text": "..."}]), the UI previously displayed
the raw Python repr string instead of the extracted text.
Replace str(msg.content) with the existing _extract_text() helper in
both _serialize_message() and stream() to properly normalize
list-of-blocks content to plain text.
Fixes #1149
Also fixes the same root cause as #1188 (characters displayed one per
line when tool response content is returned as structured blocks).
Added 11 regression tests covering string, list-of-blocks, mixed,
empty, and fallback content types.
* fix(memory): extract text from structured LLM responses in memory updater
When LLMs return response content as list of content blocks
(e.g. [{"type": "text", "text": "..."}]) instead of plain strings,
str() produces Python repr which breaks JSON parsing in the memory
updater. This caused memory updates to silently fail.
Changes:
- Add _extract_text() helper in updater.py for safe content normalization
- Use _extract_text() instead of str(response.content) in update_memory()
- Fix format_conversation_for_update() to handle plain strings in list content
- Fix subagent executor fallback path to extract text from list content
- Replace print() with structured logging (logger.info/warning/error)
- Add 13 regression tests covering _extract_text, format_conversation,
and update_memory with structured LLM responses
* fix: address Copilot review - defensive text extraction + logger.exception
- client.py _extract_text: use block.get('text') + isinstance check (prevent KeyError/TypeError)
- prompt.py format_conversation_for_update: same defensive check for dict text blocks
- executor.py: type-safe text extraction in both code paths, fallback to placeholder instead of str(raw_content)
- updater.py: use logger.exception() instead of logger.error() for traceback preservation
* Apply suggestions from code review
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* fix: preserve chunked structured content without spurious newlines
* fix: restore backend unit test compatibility
---------
Co-authored-by: Exploreunive <Exploreunive@users.noreply.github.com>
Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-03-22 17:29:29 +08:00
|
|
|
assert _extract_text(content) == '{"user": "alice"}'
|
|
|
|
|
|
|
|
|
|
def test_list_mixed_strings_and_blocks(self):
|
|
|
|
|
content = [
|
|
|
|
|
"raw text",
|
|
|
|
|
{"type": "text", "text": "block text"},
|
|
|
|
|
]
|
|
|
|
|
assert _extract_text(content) == "raw text\nblock text"
|
|
|
|
|
|
|
|
|
|
def test_list_adjacent_string_chunks_then_block(self):
|
|
|
|
|
content = [
|
|
|
|
|
"prefix",
|
|
|
|
|
"-continued",
|
|
|
|
|
{"type": "text", "text": "block text"},
|
|
|
|
|
]
|
|
|
|
|
assert _extract_text(content) == "prefix-continued\nblock text"
|
|
|
|
|
|
|
|
|
|
def test_list_skips_non_text_blocks(self):
|
|
|
|
|
content = [
|
|
|
|
|
{"type": "image_url", "image_url": {"url": "http://img.png"}},
|
|
|
|
|
{"type": "text", "text": "actual text"},
|
|
|
|
|
]
|
|
|
|
|
assert _extract_text(content) == "actual text"
|
|
|
|
|
|
|
|
|
|
def test_empty_list(self):
|
|
|
|
|
assert _extract_text([]) == ""
|
|
|
|
|
|
|
|
|
|
def test_list_no_text_blocks(self):
|
|
|
|
|
assert _extract_text([{"type": "image_url", "image_url": {}}]) == ""
|
|
|
|
|
|
|
|
|
|
def test_non_str_non_list(self):
|
|
|
|
|
assert _extract_text(42) == "42"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
# format_conversation_for_update — handles mixed list content
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class TestFormatConversationForUpdate:
|
|
|
|
|
def test_plain_string_messages(self):
|
|
|
|
|
human_msg = MagicMock()
|
|
|
|
|
human_msg.type = "human"
|
|
|
|
|
human_msg.content = "What is Python?"
|
|
|
|
|
|
|
|
|
|
ai_msg = MagicMock()
|
|
|
|
|
ai_msg.type = "ai"
|
|
|
|
|
ai_msg.content = "Python is a programming language."
|
|
|
|
|
|
|
|
|
|
result = format_conversation_for_update([human_msg, ai_msg])
|
|
|
|
|
assert "User: What is Python?" in result
|
|
|
|
|
assert "Assistant: Python is a programming language." in result
|
|
|
|
|
|
|
|
|
|
def test_list_content_with_plain_strings(self):
|
|
|
|
|
"""Plain strings in list content should not be lost."""
|
|
|
|
|
msg = MagicMock()
|
|
|
|
|
msg.type = "human"
|
|
|
|
|
msg.content = ["raw user text", {"type": "text", "text": "structured text"}]
|
|
|
|
|
|
|
|
|
|
result = format_conversation_for_update([msg])
|
|
|
|
|
assert "raw user text" in result
|
|
|
|
|
assert "structured text" in result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
# update_memory — structured LLM response handling
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class TestUpdateMemoryStructuredResponse:
|
|
|
|
|
"""update_memory should handle LLM responses returned as list content blocks."""
|
|
|
|
|
|
|
|
|
|
def _make_mock_model(self, content):
|
|
|
|
|
model = MagicMock()
|
|
|
|
|
response = MagicMock()
|
|
|
|
|
response.content = content
|
|
|
|
|
model.invoke.return_value = response
|
|
|
|
|
return model
|
|
|
|
|
|
|
|
|
|
def test_string_response_parses(self):
|
|
|
|
|
updater = MemoryUpdater()
|
|
|
|
|
valid_json = '{"user": {}, "history": {}, "newFacts": [], "factsToRemove": []}'
|
|
|
|
|
|
|
|
|
|
with (
|
|
|
|
|
patch.object(updater, "_get_model", return_value=self._make_mock_model(valid_json)),
|
|
|
|
|
patch("deerflow.agents.memory.updater.get_memory_config", return_value=_memory_config(enabled=True)),
|
|
|
|
|
patch("deerflow.agents.memory.updater.get_memory_data", return_value=_make_memory()),
|
|
|
|
|
patch("deerflow.agents.memory.updater._save_memory_to_file", return_value=True),
|
|
|
|
|
):
|
|
|
|
|
msg = MagicMock()
|
|
|
|
|
msg.type = "human"
|
|
|
|
|
msg.content = "Hello"
|
|
|
|
|
ai_msg = MagicMock()
|
|
|
|
|
ai_msg.type = "ai"
|
|
|
|
|
ai_msg.content = "Hi there"
|
|
|
|
|
ai_msg.tool_calls = []
|
|
|
|
|
result = updater.update_memory([msg, ai_msg])
|
|
|
|
|
|
|
|
|
|
assert result is True
|
|
|
|
|
|
|
|
|
|
def test_list_content_response_parses(self):
|
|
|
|
|
"""LLM response as list-of-blocks should be extracted, not repr'd."""
|
|
|
|
|
updater = MemoryUpdater()
|
|
|
|
|
valid_json = '{"user": {}, "history": {}, "newFacts": [], "factsToRemove": []}'
|
|
|
|
|
list_content = [{"type": "text", "text": valid_json}]
|
|
|
|
|
|
|
|
|
|
with (
|
|
|
|
|
patch.object(updater, "_get_model", return_value=self._make_mock_model(list_content)),
|
|
|
|
|
patch("deerflow.agents.memory.updater.get_memory_config", return_value=_memory_config(enabled=True)),
|
|
|
|
|
patch("deerflow.agents.memory.updater.get_memory_data", return_value=_make_memory()),
|
|
|
|
|
patch("deerflow.agents.memory.updater._save_memory_to_file", return_value=True),
|
|
|
|
|
):
|
|
|
|
|
msg = MagicMock()
|
|
|
|
|
msg.type = "human"
|
|
|
|
|
msg.content = "Hello"
|
|
|
|
|
ai_msg = MagicMock()
|
|
|
|
|
ai_msg.type = "ai"
|
|
|
|
|
ai_msg.content = "Hi"
|
|
|
|
|
ai_msg.tool_calls = []
|
|
|
|
|
result = updater.update_memory([msg, ai_msg])
|
|
|
|
|
|
|
|
|
|
assert result is True
|