Untitled conversation
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
# tree_app_refactored.py
# Python 3.12+ / Flet 0.28.3
from __future__ import annotations
import uuid
from collections import defaultdict
from typing import Callable, List, Optional
import flet as ft
from pydantic import BaseModel, Field
# ────────────────────────────── Domain layer ──────────────────────────────────
class TreeNode(BaseModel):
"""
Single conversation unit.
• `reasoning` : chain-of-thought
• `response` : final text shown to user
• `children` : next turns of the same branch
UI とは無関係に階層・ナビゲーションを管理できるように振る舞いを持たせる。
"""
id: str = Field(default_factory=lambda: str(uuid.uuid4()))
role: str
reasoning: str
response: str
children: List["TreeNode"] = Field(default_factory=list)
active_index: int = 0 # currently selected child
# ----- traversal ----------------------------------------------------------
@property
def active_child(self) -> Optional["TreeNode"]:
if not self.children:
return None
self._clamp_index()
return self.children[self.active_index]
# navigation behaviour kept inside the entity
def next_child(self) -> None:
if self.children:
self.active_index = min(self.active_index + 1, len(self.children) - 1)
def prev_child(self) -> None:
if self.children:
self.active_index = max(self.active_index - 1, 0)
# ----- helpers ------------------------------------------------------------
def _clamp_index(self) -> None:
self.active_index = min(max(self.active_index, 0), len(self.children) - 1)
class Tree(BaseModel):
"""
Forest-level aggregate root.
1. どの root が選択されているか (`active_tree_index`)
2. root → active_child → … と辿った "現在のパス" を返す API がある
"""
root_nodes: List[TreeNode] = Field(default_factory=list)
active_tree_index: int = 0
def active_path(self) -> List[TreeNode]:
if not self.root_nodes:
return []
self.active_tree_index = min(
max(self.active_tree_index, 0), len(self.root_nodes) - 1
)
path: List[TreeNode] = []
node: Optional[TreeNode] = self.root_nodes[self.active_tree_index]
while node:
path.append(node)
node = node.active_child
return path
# ───────────────────────────── Event bus ──────────────────────────────────────
class EventBus:
"""
Very small publish/subscribe hub.
No threading: every callback runs synchronously on the UI thread.
"""
def __init__(self) -> None:
self._subs: dict[str, list[Callable]] = defaultdict(list)
def sub(self, topic: str, fn: Callable) -> None:
self._subs[topic].append(fn)
def pub(self, topic: str, data=None) -> None:
for fn in self._subs.get(topic, []):
fn(data)
# ──────────────────────────── Application service ─────────────────────────────
class TreeService:
"""
Single façade the UI talks to.
Encapsulates *all* state changes and notifies the rest of the app.
"""
def __init__(self, tree: Tree, bus: EventBus) -> None:
self._tree = tree
self._bus = bus
# ----- mutation API -------------------------------------------------------
def update_text(
self, node: TreeNode, reasoning: str, response: str, *, snack_msg=True
) -> None:
node.reasoning, node.response = reasoning, response
self._bus.pub("state_changed")
if snack_msg:
self._bus.pub("snackbar", "ノードを更新しました")
def next_sibling(self, parent: TreeNode) -> None:
parent.next_child()
self._bus.pub("state_changed")
def prev_sibling(self, parent: TreeNode) -> None:
parent.prev_child()
self._bus.pub("state_changed")
# ----- query API ----------------------------------------------------------
def active_path(self) -> List[TreeNode]:
return self._tree.active_path()
# ──────────────────────────────── UI layer ────────────────────────────────────
class ChatCard(ft.Card):
"""Editable view for a single TreeNode with display/edit mode toggle."""
def __init__(
self,
node: TreeNode,
parent_node: Optional[TreeNode],
service: TreeService,
*args,
**kwargs,
):
self._node = node
self._parent = parent_node
self._svc = service
self._edit_mode = False
self._original_reasoning = ""
self._original_response = ""
# TextFields for edit mode
self.reasoning_tf = ft.TextField(
label="Reasoning", multiline=True, expand=True
)
self.response_tf = ft.TextField(
label="Response", multiline=True, expand=True
)
# Build initial content with padding container
inner_content = self._build_content()
padded_content = ft.Container(
content=inner_content,
padding=ft.padding.all(16) # または padding=16
)
super().__init__(content=padded_content, *args, **kwargs)
def _build_content(self) -> ft.Control:
# Header with role and controls
header_controls: list[ft.Control] = [
ft.Text(value=self._node.role, style=ft.TextThemeStyle.TITLE_SMALL),
ft.Container(expand=True)
]
# Edit mode toggle button (placed before navigation arrows)
if self._edit_mode:
edit_btn = ft.IconButton(
icon=ft.Icons.EDIT,
icon_color=ft.Colors.RED,
on_click=self._cancel_and_exit,
tooltip="編集をキャンセル",
)
else:
# 通常時は編集ボタンとして表示
edit_btn = ft.IconButton(
icon=ft.Icons.EDIT,
on_click=self._enter_edit_mode,
tooltip="編集モード",
)
header_controls.append(edit_btn)
# Navigation arrows for siblings
if self._parent and len(self._parent.children) > 1:
left_btn = ft.IconButton(
icon=ft.Icons.CHEVRON_LEFT,
on_click=lambda _: self._svc.prev_sibling(self._parent),
disabled=self._parent.active_index == 0,
tooltip="前の兄弟ノードへ",
)
right_btn = ft.IconButton(
icon=ft.Icons.CHEVRON_RIGHT,
on_click=lambda _: self._svc.next_sibling(self._parent),
disabled=self._parent.active_index >= len(self._parent.children) - 1,
tooltip="次の兄弟ノードへ",
)
header_controls.extend([
left_btn,
ft.Text(
f"{self._parent.active_index + 1}/{len(self._parent.children)}",
style=ft.TextThemeStyle.BODY_SMALL,
),
right_btn,
])
header = ft.Row(header_controls, alignment=ft.MainAxisAlignment.START)
# Body content based on mode
if self._edit_mode:
# Edit mode - show TextFields and action buttons
update_btn = ft.FilledButton(
text="更新",
on_click=self._update_and_exit,
)
cancel_btn = ft.OutlinedButton(
text="キャンセル",
on_click=self._cancel_and_exit,
)
buttons = ft.Row([ft.Container(expand=True), cancel_btn, update_btn], spacing=8)
body = ft.Column([
header,
self.reasoning_tf,
self.response_tf,
buttons
], spacing=8)
else:
# Display mode - show compact Text widgets
body_controls: List[ft.Control] = [header]
if self._node.reasoning:
body_controls.append(ft.ExpansionTile(
title=ft.Text(value="Reasoning", style=ft.TextThemeStyle.LABEL_MEDIUM),
controls=[ft.Text(
value=self._node.reasoning,
style=ft.TextThemeStyle.BODY_MEDIUM,
selectable=True,
)]))
if self._node.response:
body_controls.append(ft.Text(
value=self._node.response,
style=ft.TextThemeStyle.BODY_MEDIUM,
selectable=True,
))
body = ft.Column(body_controls, spacing=4)
return body
def _enter_edit_mode(self, _):
"""Enter edit mode and save original values for potential cancellation."""
self._edit_mode = True
self._original_reasoning = self._node.reasoning
self._original_response = self._node.response
self.reasoning_tf.value = self._node.reasoning
self.response_tf.value = self._node.response
self._rebuild()
def _update_and_exit(self, _):
"""Update the node and exit edit mode."""
self._svc.update_text(
self._node,
self.reasoning_tf.value,
self.response_tf.value
)
self._edit_mode = False
def _cancel_and_exit(self, _):
"""Cancel editing and exit edit mode without saving changes."""
self._edit_mode = False
# Restore original values (no actual changes to node)
self.reasoning_tf.value = self._original_reasoning
self.response_tf.value = self._original_response
self._rebuild()
def _rebuild(self):
"""Rebuild the card content."""
inner_content = self._build_content()
self.content = ft.Container(
content=inner_content,
padding=ft.padding.all(16)
)
self.update()
# ────────────────────────── Demo tree constructor ─────────────────────────────
def build_demo_tree() -> Tree:
root = TreeNode(role="system", reasoning="", response="こんにちは!何かお手伝いできることはありますか?")
a = TreeNode(role="user", reasoning="", response="明日の天気は?")
b = TreeNode(role="user", reasoning="", response="東京への行き方は?")
c = TreeNode(role="user", reasoning="", response="おでんの具で一番美味しいのは?")
root.children = [a, b, c]
root.active_index = 1 # 'b' is selected
b1 = TreeNode(role="assistant", reasoning="[東京への行き方を考える]", response="すみません、よくわかりませんでした。")
b2 = TreeNode(role="assistant", reasoning="[東京への行き方を考える]", response="好きに行けばいいと思います。")
b.children = [b1, b2]
return Tree(root_nodes=[root])
# ──────────────────────────────── Flet main ───────────────────────────────────
def main(page: ft.Page) -> None:
page.title = "TreeNode Active Path (display/edit modes)"
page.scroll = ft.ScrollMode.AUTO
bus = EventBus()
service = TreeService(build_demo_tree(), bus)
body_column = ft.Column(spacing=12)
page.add(body_column)
# Rebuild UI whenever the state changes
def rebuild_body(_=None):
body_column.controls.clear()
path = service.active_path()
for depth, node in enumerate(path):
parent = path[depth - 1] if depth > 0 else None
body_column.controls.append(
ChatCard(node=node, parent_node=parent, service=service)
)
page.update()
bus.sub("state_changed", rebuild_body)
rebuild_body() # initial render
# Snackbar listener
def show_snackbar(msg: str):
page.snack_bar = ft.SnackBar(content=ft.Text(msg), open=True)
page.update()
bus.sub("snackbar", show_snackbar)
# ------------------------------------------------------------------------------
if __name__ == "__main__":
ft.app(target=main)
Python 3.12+, Flet 0.28.3. 機能を完全に維持したまま、コードを読みやすく・変更しやすくリファクタリングして。
コードを分析して、機能を完全に維持しながら読みやすさと変更しやすさを向上させるリファクタリングを行いました。
# tree_app_refactored.py
# Python 3.12+ / Flet 0.28.3
from __future__ import annotations
import uuid
from collections import defaultdict
from typing import Callable, List, Optional
import flet as ft
from pydantic import BaseModel, Field
# ────────────────────────────── Domain layer ──────────────────────────────────
class TreeNode(BaseModel):
"""
Single conversation unit with navigation capabilities.
Manages hierarchical structure and child navigation independently of UI.
"""
id: str = Field(default_factory=lambda: str(uuid.uuid4()))
role: str
reasoning: str
response: str
children: List["TreeNode"] = Field(default_factory=list)
active_index: int = 0
@property
def active_child(self) -> Optional["TreeNode"]:
"""Get currently selected child node."""
if not self.children:
return None
self._ensure_valid_index()
return self.children[self.active_index]
@property
def has_siblings(self) -> bool:
"""Check if this node has multiple siblings (used by parent)."""
return len(self.children) > 1
@property
def sibling_info(self) -> tuple[int, int]:
"""Get current position and total count of children."""
return self.active_index + 1, len(self.children)
def navigate_to_next_child(self) -> bool:
"""Navigate to next child. Returns True if navigation occurred."""
if not self.children:
return False
old_index = self.active_index
self.active_index = min(self.active_index + 1, len(self.children) - 1)
return old_index != self.active_index
def navigate_to_prev_child(self) -> bool:
"""Navigate to previous child. Returns True if navigation occurred."""
if not self.children:
return False
old_index = self.active_index
self.active_index = max(self.active_index - 1, 0)
return old_index != self.active_index
def can_navigate_next(self) -> bool:
"""Check if can navigate to next child."""
return self.children and self.active_index < len(self.children) - 1
def can_navigate_prev(self) -> bool:
"""Check if can navigate to previous child."""
return self.children and self.active_index > 0
def update_content(self, reasoning: str, response: str) -> None:
"""Update node content."""
self.reasoning = reasoning
self.response = response
def _ensure_valid_index(self) -> None:
"""Ensure active_index is within valid bounds."""
if self.children:
self.active_index = max(0, min(self.active_index, len(self.children) - 1))
class Tree(BaseModel):
"""
Tree aggregate root managing multiple conversation trees.
"""
root_nodes: List[TreeNode] = Field(default_factory=list)
active_tree_index: int = 0
def get_active_path(self) -> List[TreeNode]:
"""Get the path from active root to current leaf."""
if not self.root_nodes:
return []
self._ensure_valid_tree_index()
path: List[TreeNode] = []
current_node: Optional[TreeNode] = self.root_nodes[self.active_tree_index]
while current_node:
path.append(current_node)
current_node = current_node.active_child
return path
def _ensure_valid_tree_index(self) -> None:
"""Ensure active_tree_index is within valid bounds."""
if self.root_nodes:
self.active_tree_index = max(0, min(self.active_tree_index, len(self.root_nodes) - 1))
# ───────────────────────────── Event system ──────────────────────────────────
class EventBus:
"""
Simple synchronous event bus for decoupled communication.
"""
def __init__(self) -> None:
self._subscribers: dict[str, list[Callable]] = defaultdict(list)
def subscribe(self, event_type: str, callback: Callable) -> None:
"""Subscribe to an event type."""
self._subscribers[event_type].append(callback)
def publish(self, event_type: str, data=None) -> None:
"""Publish an event to all subscribers."""
for callback in self._subscribers.get(event_type, []):
callback(data)
# ──────────────────────────── Application service ─────────────────────────────
class TreeService:
"""
Application service managing tree operations and state changes.
"""
def __init__(self, tree: Tree, event_bus: EventBus) -> None:
self._tree = tree
self._event_bus = event_bus
def update_node_content(
self,
node: TreeNode,
reasoning: str,
response: str,
*,
show_notification: bool = True
) -> None:
"""Update node content and notify subscribers."""
node.update_content(reasoning, response)
self._notify_state_changed()
if show_notification:
self._event_bus.publish("notification", "ノードを更新しました")
def navigate_to_next_sibling(self, parent_node: TreeNode) -> None:
"""Navigate to next sibling and notify if changed."""
if parent_node.navigate_to_next_child():
self._notify_state_changed()
def navigate_to_prev_sibling(self, parent_node: TreeNode) -> None:
"""Navigate to previous sibling and notify if changed."""
if parent_node.navigate_to_prev_child():
self._notify_state_changed()
def get_active_conversation_path(self) -> List[TreeNode]:
"""Get the current active conversation path."""
return self._tree.get_active_path()
def _notify_state_changed(self) -> None:
"""Notify subscribers that state has changed."""
self._event_bus.publish("state_changed")
# ──────────────────────────────── UI Components ────────────────────────────────
class EditableContent:
"""Manages editable content state and operations."""
def __init__(self, initial_reasoning: str, initial_response: str):
self.reasoning_field = ft.TextField(
label="Reasoning",
multiline=True,
expand=True,
value=initial_reasoning
)
self.response_field = ft.TextField(
label="Response",
multiline=True,
expand=True,
value=initial_response
)
self._original_reasoning = initial_reasoning
self._original_response = initial_response
def get_current_values(self) -> tuple[str, str]:
"""Get current field values."""
return self.reasoning_field.value or "", self.response_field.value or ""
def reset_to_original(self) -> None:
"""Reset fields to original values."""
self.reasoning_field.value = self._original_reasoning
self.response_field.value = self._original_response
def update_values(self, reasoning: str, response: str) -> None:
"""Update field values and store as new originals."""
self.reasoning_field.value = reasoning
self.response_field.value = response
self._original_reasoning = reasoning
self._original_response = response
class NavigationControls:
"""Creates navigation controls for sibling nodes."""
@staticmethod
def create_sibling_navigation(
parent_node: TreeNode,
service: TreeService
) -> List[ft.Control]:
"""Create navigation controls if parent has multiple children."""
if not parent_node or not parent_node.has_siblings:
return []
current_pos, total_count = parent_node.sibling_info
return [
ft.IconButton(
icon=ft.Icons.CHEVRON_LEFT,
on_click=lambda _: service.navigate_to_prev_sibling(parent_node),
disabled=not parent_node.can_navigate_prev(),
tooltip="前の兄弟ノードへ",
),
ft.Text(
f"{current_pos}/{total_count}",
style=ft.TextThemeStyle.BODY_SMALL,
),
ft.IconButton(
icon=ft.Icons.CHEVRON_RIGHT,
on_click=lambda _: service.navigate_to_next_sibling(parent_node),
disabled=not parent_node.can_navigate_next(),
tooltip="次の兄弟ノードへ",
),
]
class ChatCard(ft.Card):
"""
Editable card component for displaying and editing TreeNode content.
"""
def __init__(
self,
node: TreeNode,
parent_node: Optional[TreeNode],
service: TreeService,
*args,
**kwargs,
):
self._node = node
self._parent_node = parent_node
self._service = service
self._is_editing = False
self._editable_content = EditableContent(node.reasoning, node.response)
super().__init__(
content=self._create_padded_content(),
*args,
**kwargs
)
def _create_padded_content(self) -> ft.Container:
"""Create main content with padding."""
return ft.Container(
content=self._build_card_content(),
padding=ft.padding.all(16)
)
def _build_card_content(self) -> ft.Column:
"""Build the main card content based on current mode."""
header = self._create_header()
if self._is_editing:
return self._create_edit_mode_content(header)
else:
return self._create_display_mode_content(header)
def _create_header(self) -> ft.Row:
"""Create the card header with role, edit button, and navigation."""
controls = [
ft.Text(value=self._node.role, style=ft.TextThemeStyle.TITLE_SMALL),
ft.Container(expand=True), # Spacer
self._create_edit_toggle_button(),
]
# Add navigation controls if applicable
nav_controls = NavigationControls.create_sibling_navigation(
self._parent_node, self._service
)
controls.extend(nav_controls)
return ft.Row(controls, alignment=ft.MainAxisAlignment.START)
def _create_edit_toggle_button(self) -> ft.IconButton:
"""Create edit/cancel toggle button."""
if self._is_editing:
return ft.IconButton(
icon=ft.Icons.EDIT,
icon_color=ft.Colors.RED,
on_click=self._handle_cancel_edit,
tooltip="編集をキャンセル",
)
else:
return ft.IconButton(
icon=ft.Icons.EDIT,
on_click=self._handle_enter_edit,
tooltip="編集モード",
)
def _create_edit_mode_content(self, header: ft.Row) -> ft.Column:
"""Create content for edit mode."""
action_buttons = ft.Row([
ft.Container(expand=True), # Spacer
ft.OutlinedButton(
text="キャンセル",
on_click=self._handle_cancel_edit,
),
ft.FilledButton(
text="更新",
on_click=self._handle_save_edit,
),
], spacing=8)
return ft.Column([
header,
self._editable_content.reasoning_field,
self._editable_content.response_field,
action_buttons
], spacing=8)
def _create_display_mode_content(self, header: ft.Row) -> ft.Column:
"""Create content for display mode."""
content_controls = [header]
# Add reasoning section if present
if self._node.reasoning:
content_controls.append(
ft.ExpansionTile(
title=ft.Text(
value="Reasoning",
style=ft.TextThemeStyle.LABEL_MEDIUM
),
controls=[ft.Text(
value=self._node.reasoning,
style=ft.TextThemeStyle.BODY_MEDIUM,
selectable=True,
)]
)
)
# Add response section if present
if self._node.response:
content_controls.append(
ft.Text(
value=self._node.response,
style=ft.TextThemeStyle.BODY_MEDIUM,
selectable=True,
)
)
return ft.Column(content_controls, spacing=4)
def _handle_enter_edit(self, _) -> None:
"""Enter edit mode."""
self._is_editing = True
self._editable_content.update_values(self._node.reasoning, self._node.response)
self._rebuild_content()
def _handle_save_edit(self, _) -> None:
"""Save changes and exit edit mode."""
reasoning, response = self._editable_content.get_current_values()
self._service.update_node_content(self._node, reasoning, response)
self._is_editing = False
def _handle_cancel_edit(self, _) -> None:
"""Cancel editing and exit edit mode."""
self._is_editing = False
self._editable_content.reset_to_original()
self._rebuild_content()
def _rebuild_content(self) -> None:
"""Rebuild the card content and update display."""
self.content = self._create_padded_content()
self.update()
# ────────────────────────── Demo data factory ─────────────────────────────
class DemoTreeFactory:
"""Factory for creating demo tree data."""
@staticmethod
def create_demo_tree() -> Tree:
"""Create a demo conversation tree."""
root = TreeNode(
role="system",
reasoning="",
response="こんにちは!何かお手伝いできることはありますか?"
)
# Create user questions
questions = [
TreeNode(role="user", reasoning="", response="明日の天気は?"),
TreeNode(role="user", reasoning="", response="東京への行き方は?"),
TreeNode(role="user", reasoning="", response="おでんの具で一番美味しいのは?"),
]
root.children = questions
root.active_index = 1 # Select "東京への行き方は?"
# Add responses to the selected question
tokyo_question = questions[1]
tokyo_responses = [
TreeNode(
role="assistant",
reasoning="[東京への行き方を考える]",
response="すみません、よくわかりませんでした。"
),
TreeNode(
role="assistant",
reasoning="[東京への行き方を考える]",
response="好きに行けばいいと思います。"
),
]
tokyo_question.children = tokyo_responses
return Tree(root_nodes=[root])
# ──────────────────────────────── Main Application ───────────────────────────────────
class TreeApp:
"""Main application controller."""
def __init__(self, page: ft.Page):
self.page = page
self.event_bus = EventBus()
self.service = TreeService(DemoTreeFactory.create