Add human in the loop notebook

This commit is contained in:
Nuno Campos
2024-02-07 20:05:05 -08:00
parent c4f87cdccd
commit 37bad4e30a
4 changed files with 529 additions and 10 deletions
+16 -4
View File
@@ -1,6 +1,6 @@
from asyncio import iscoroutinefunction
from collections import defaultdict
from typing import Any, Callable, Dict, NamedTuple, Optional
from typing import Any, Callable, Dict, NamedTuple, Optional, Sequence
from langchain_core.runnables import Runnable
from langchain_core.runnables.base import (
@@ -88,7 +88,7 @@ class Graph:
def set_finish_point(self, key: str) -> None:
return self.add_edge(key, END)
def validate(self) -> None:
def validate(self, interrupt: Optional[Sequence[str]] = None) -> None:
all_starts = {src for src, _ in self.edges} | {src for src in self.branches}
for node in self.nodes:
if node not in all_starts:
@@ -114,8 +114,17 @@ class Graph:
if node not in all_ends:
raise ValueError(f"Node `{node}` is not reachable")
def compile(self, checkpointer: Optional[BaseCheckpointSaver] = None) -> Pregel:
self.validate()
if interrupt:
for node in interrupt:
if node not in self.nodes:
raise ValueError(f"Node `{node}` is not present")
def compile(
self,
checkpointer: Optional[BaseCheckpointSaver] = None,
interrupt_before: Optional[Sequence[str]] = None,
) -> Pregel:
self.validate(interrupt=interrupt_before)
outgoing_edges = defaultdict(list)
for start, end in self.edges:
@@ -145,4 +154,7 @@ class Graph:
output=END,
hidden=[f"{node}:inbox" for node in self.nodes],
checkpointer=checkpointer,
interrupt=[f"{node}:inbox" for node in interrupt_before]
if interrupt_before
else [],
)
+10 -3
View File
@@ -1,7 +1,7 @@
from collections import defaultdict
from functools import partial
from inspect import signature
from typing import Any, Optional, Type
from typing import Any, Optional, Sequence, Type
from langchain_core.runnables import RunnableLambda, RunnablePassthrough
from langchain_core.runnables.base import RunnableLike
@@ -34,8 +34,12 @@ class StateGraph(Graph):
)
return super().add_node(key, action)
def compile(self, checkpointer: Optional[BaseCheckpointSaver] = None) -> Pregel:
self.validate()
def compile(
self,
checkpointer: Optional[BaseCheckpointSaver] = None,
interrupt_before: Optional[Sequence[str]] = None,
) -> Pregel:
self.validate(interrupt=interrupt_before)
state_keys = list(self.channels)
state_keys_read = state_keys[0] if state_keys == ["__root__"] else state_keys
@@ -98,6 +102,9 @@ class StateGraph(Graph):
output=END,
hidden=[f"{node}:inbox" for node in self.nodes] + [START] + state_keys,
checkpointer=checkpointer,
interrupt=[f"{node}:inbox" for node in interrupt_before]
if interrupt_before
else [],
)