Source code for langchain_experimental.tot.controller
from typing import Tuple
from langchain_experimental.tot.memory import ToTDFSMemory
from langchain_experimental.tot.thought import ThoughtValidity
[docs]class ToTController:
"""思维树(ToT)控制器。
这是ToT控制器的一个版本,在论文中被称为“简单控制器”。
它有一个参数`c`,表示每个思维要探索的子节点数量。"""
[docs] def __init__(self, c: int = 3):
"""初始化控制器。
参数:
c:每个节点要探索的子节点数量。
"""
self.c = c
def __call__(self, memory: ToTDFSMemory) -> Tuple[str, ...]:
next_thought = memory.top()
parent_thought = memory.top_parent()
validity = (
ThoughtValidity.VALID_INTERMEDIATE
if next_thought is None
else next_thought.validity
)
# 1 if the current partial solution is invalid, backtrack to the parent
# thought.
if validity == ThoughtValidity.INVALID:
memory.pop()
next_thought = memory.top()
if next_thought and len(next_thought.children) >= self.c:
memory.pop()
# 2 if the current partial solution is valid but C children were
# explored and yet failed to find a final solution, backtrack to the
# parent thought.
elif (
validity == ThoughtValidity.VALID_INTERMEDIATE
and parent_thought
and len(parent_thought.children) >= self.c
):
memory.pop(2)
return tuple(thought.text for thought in memory.current_path())