Repository navigation
feat: Directly reply to add chart type - #8307
Conversation
| return to_text(value) | ||
|
|
||
| def to_content_list(self, answer, node_info: NodeInfo, position: Position) -> List[Content]: | ||
| return [EchartsContent(str(uuid.uuid7()), answer, Status.SUCCESS, node_info, position)] |
There was a problem hiding this comment.
Review of echarts_reply.py
Potential Issues
-
uuid_utils.compat as uuidis unusual for a standard libraryuuid.uuid7()— confirm that theuuid_utils.compatshim actually exposesuuid7(). The stdlibuuidmodule (even in Python 3.12+) does not haveuuid7(). If the compat layer doesn't provide it, this will fail at runtime withAttributeError.- Consider whether
uuid_utilsis a declared dependency inpyproject.toml/requirements.txt.
-
json.dumpsmay raise on non-serializable values- If
valueis adict/listcontainingdatetime,Decimal, sets, custom objects, etc.,json.dumpswill throwTypeError. Given this is chart data coming from workflow variables, types likedatetimeare plausible. - Suggest a
default=fallback (e.g.,default=str) or wrap in try/except and fall back toto_text(value).
- If
-
No type annotations on method signatures
support(self, content_type: str) -> boolis annotated, butget_answer(self, node, value)andto_content_list(...)have untypednode,value,answer.answer: strandnode: Nodereturn typeList[Content]would improve readability and static checking, consistent withsupport.
-
Unused import concern / coupling
- Verify
NodeInfo,Position,Status,EchartsContent,to_textare all actually needed (they appear to be). No dead imports obvious, butjsonis imported unconditionally even though the textual path doesn't need it (minor).
- Verify
-
Header comment inconsistency
- Docstring says
@date:2026/12/4while the diff header shows2026/12/4— fine, but mixed full-width colon (:) and ASCII:in the docstring tags (@Author:vs@file:). Cosmetic consistency suggestion.
- Docstring says
-
Magic string
"ECHARTS"- Repeated verbatim; if other handlers use the same pattern this is acceptable, but consider an enum/shared constant to avoid typos across handlers.
-
to_content_listalways reportsStatus.SUCCESS- Confirm this is intentional.
EchartsReplyproducingSUCCESSregardless of input seems acceptable since rendering is client-side, but worth double-checking no error propagation is expected here.
- Confirm this is intentional.
-
on the springboard:str(uuid.uuid7())twice? No — called once per invocation, fine.
Optimization Suggestions
- Add a serialization guard:
def get_answer(self, node, value): if isinstance(value, (dict, list)): try: return json.dumps(value, ensure_ascii=False, default=str) except TypeError: return to_text(value) return to_text(value)
- Add type hints to
get_answer(value: Any -> str,node: Node),to_content_list(answer: str) to match the style used insupport. - Optionally make the JSON serializer configurable (separators, indent) if humans may inspect raw output.
- Consider moving the ECharts content-type literal to a shared constant.
- Ensure
uuid_utilsis pinned in dependencies; alternatively usefrom uuid import uuid4for broad compatibility if v7 semantics aren't required.
Overall the file is small and clean; the main risks are uuid7 availability and JSON-serialization exceptions for non-JSON-native workflow variables.
| chunk.status or prev.status, | ||
| chunk.node_info or prev.node_info, | ||
| chunk.position or prev.position, | ||
| ) |
There was a problem hiding this comment.
Code Review: EchartsAggregator
Potential Issues
1. chunk.id or prev.id — ID overwrite semantics
The aggregation picks chunk.id whenever it's truthy, which means the last chunk's id wins. If ContentAggregator downstream logic relies on stable identity (e.g., deduplication, keying), this may cause instability across chunks. If id should remain constant for the whole aggregated message, use prev.id or chunk.id. Confirm intent.
Suggestion: Make the precedence explicit and document it:
return EchartsContent(
id=prev.id or chunk.id, # keep original identity if id is meant to be stable
content=(prev.content or "") + (chunk.content or ""),
...
)2. Positional constructor arguments are fragile
EchartsContent(...) is called positionally, relying on field order of a dataclass/namedtuple. Any future reordering of fields silently breaks aggregation. Use keyword arguments.
3. Fields are dropped / not handled
Only id, content, status, node_info, position are aggregated. If EchartsContent has other fields (timestamps, metadata, error info, done/is_end flags), they are silently discarded from chunk. Verify all relevant fields are carried over.
4. prev is None branch returns chunk by reference
Returning the incoming chunk directly means the caller receives an object aliased with the input. If either side mutates later, state can leak. If EchartsContent is immutable (frozen dataclass / namedtuple) this is fine; otherwise consider copying.
5. status or prev.status precedence
Like id, later status wins. That's usually correct for streaming, but make sure a partial status ("running") doesn't override a terminal one ("success"). Consider explicit status-merge logic if status is an enum with severity/terminal states (e.g., never downgrade DONE → RUNNING).
6. String concatenation in a loop — O(n²) risk
If aggregate is invoked once per chunk in a stream, (prev.content or "") + (chunk.content or "") rebuilds the full buffer each time → quadratic behavior on large outputs. For typical chat payloads it's fine, but for large charts/long streams, accumulate into a list/buffer and join at the end.
Optimization: store chunks in a list and join lazily, or use ''.join in a finalizer step.
7. Docstring mentions <echarts_rander> — typo
"rander" is likely "render". Also the docstring claims "按顺序拼接内容块" (concatenate content blocks in order), which matches content handling — good, but ensure tags/separators are not required between chunks (e.g., a chunk split mid-</echarts_render> fully qualified tag boundary). Mid-tag splits just work with plain concatenation only if the tag stream itself is being reassembled here — confirm the renderer tolerates arbitrary split points.
8. Missing type hints robustness
prev: EchartsContent yet the code checks prev is None. The signature should be prev: EchartsContent | None = None (or Optional) to match reality, unless the ABC contract forbids None.
9. No regressions tests visible
No unit tests in the diff. Add coverage for: first-chunk (prev=None), empty content, mixed None status/node_info, and multi-chunk concatenation.
10. Encoding/coding declaration
# coding=utf-8 is redundant in Python 3 (UTF-8 is the default). Harmless, but could be removed for consistency with PEP 3120.
Minor / Style
- Import ordering:
application.workflow.message.aggregator...beforestruct...is fine, but check project isort config. - File header
@file:uses a full-width colon (:); cosmetic inconsistency with@project:/@date:.
Summary of Recommended Changes
def aggregate(self, prev: Optional[EchartsContent], chunk: EchartsContent) -> EchartsContent:
if prev is None:
return chunk
return EchartsContent(
id=chunk.id or prev.id,
content=(prev.content or "") + (chunk.content or ""),
status=chunk.status or prev.status,
node_info=chunk.node_info or prev.node_info,
position=chunk.position or prev.position,
)Plus: confirm field completeness, add tests, and consider buffered concatenation for large streams.
| def to_dict(self): | ||
| result = super().to_dict() | ||
| result["content"] = self.content | ||
| return result |
There was a problem hiding this comment.
Here's my review:
Potential Issues
-
Inconsistent state handling:
self.contentis set beforesuper().__init__(). If the parent constructor raises an exception,self.contentis still partially initialized. More importantly, if the base class'sto_dict()or other logic relies on acontentattribute, ordering matters. Consider callingsuper().__init__()first, then assigning. -
contentnot validated/typed strictly: The type hint saysstr, but there's no validation. If callers passNoneor a dict (some ECharts payloads are objects), it silently propagates. Consider validating or documenting expected format (JSON string vs. dict). -
Mutating shared state in
to_dict: Assumingsuper().to_dict()returns a fresh dict this is fine, but if it ever returns a cached/shared reference, you'd be mutating it. Worth confirming the parent contract. -
Missing
Optional/defaults: No defaults forstatus,node_info,position— callers must always supply them. Fine if intentional, but consider keyword-only args for readability given the positional_id, content. -
No
__slots__(minor): If many instances exist and the base supports it, adding__slots__ = ('content',)reduces memory. -
No
repr/equality: Minor; depends on base class behavior.
Style/Optimization Suggestions
- Move
super().__init__()beforeself.content = contentfor safer initialization ordering. - Add a docstring to
__init__andto_dictexplaining thecontentfield's expected format (raw JSON string of ECharts option). - Consider making
contenta property or validating it's valid JSON if the frontend requires it. - The file header date/naming with full-width colon (
@file:) is inconsistent — use ASCII:. - Add unit tests verifying
to_dict()output contains both parent keys andcontent.
Summary: The main actionable items are the init-order concern and the lack of validation/documentation around content. Everything else is minor.
feat: Directly reply to add chart type