準備

import operator
from typing import Annotated, Any
from langchain_core.messages import SystemMessage, HumanMessage, BaseMessage

class State(BaseModel):
"""ステートの雛形"""
query: str = Field(default = "", description = "ユーザーの質問")
messages: Annotated[list[BaseMessage], operator.add] = Field(default = [])

def state_llm(state: State) -> dict[str, Any]:
"""ノードである状態の一つ"""
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.4)
message = llm.invoke(state.messages)
return {"messages": [message]}
from langgraph.graph import StateGraph

graph = StateGraph(State)

ノードの追加

graph.add_node("ノードの名前", function_name_as_node)

エッジの追加

graph.add_edge("ソースとなるノード名", "ターゲットとなるノード名")

始点と終点

graph.set_entry_point("ノード名")
# または
# from langgraph.graph import START
# graph.add_edge(START, "ノード名")
from langgraph.graph import END

graph.add_edge("ソースとなるノード名", END)

分岐

graph.add_conditional_edges(
"ノード名",
lambda state: ブール値,
{True: "ノードT", False: "ノードF"}
)

コンパイルと実行

compiled_graph = graph.compile()

initial_state = State(query = "クエリ")
result = compiled.invoke(initial_state)