LangGraph
Graph
Node: State を受け取って更新差分を返す関数
def func_node(state: dict | BaseModel, config: RunnableConfig | None) -> dict
State
Edge
Reducer
Node からの返り値をどのように State に適用するか
State のフィールドの型ヒント Annotated で指定する、なければ単に上書き
Send
add_conditional_edge の path (router 的なもの) の Callable から返す
数が動的に変わるときに使いたいので大抵 list[Send] を返す
[Send("next_node_name", { ... } for s in state['hoge']) ]
path の type hint 的に返すのは list[Hashable]
Command
Node の返り値、状態の更新と次のノードを同時に返す
goto に Node 名だけでなく Send や list[Send] も渡せる
update, goto, resume, graph
デバッグ
graph.invoke(init_state, debug=True)
SubGraph
もう実装こなれてる?
MapReduce 的フロー
node は一通り登録する
add_conditional_edge
Pydantic State は *スキーマ*
Currently, the output of the graph will **NOT** be an instance of a pydantic model.
Run-time validation only occurs on **inputs** into nodes, not on the outputs.
あくまで入力値のスキーマで Pydantic オブジェクトが渡っているわけではない
Annotated による reducer や default 等は機能する
State にメソッド生やしても使えるわけではない
graph.invoke の返り値は langgraph.pregel.io.AddableValuesDict である
State.model_validate(output) してうまくいくことが保証される? かは未確認
なんか誤解しそうだし State は TypedDict でもいい気はするなあ
structured output でやりとりするところはどうせ description 読ませたいし BaseModel 使う
Config に値を入れておく
例えばモデルを取得する関数とか
ConfigSchema を定義しておくと渡せる内容が明確になる
{"configurable": <ConigSchema 型>} を渡して invoke
configurable は RunnableConfig の自由に使える領域
code:invoke_with_config.py
workflow = StateGraph(State, ConfigSchema)
...
graph = workflow.compile()
config = {"configurable": {"system_message": "respond in italian"}}
Node 側では dict として読む
code:node_with_config.py
def my_node(state: AgentState, config: RunnableConfig):
...
コンパイルした型、CompiledGraph, CompiledStateGraph は langgraph.graph.state にある、ちょいめんど
toolsCondition
import { toolsCondition } from "@langchain/langgraph/prebuilt";
message の最後に tool 呼び出しがあれば tools を返すし
ReactAgent で状態更新
prebuilt にある agent と tools をいったりきたりするだけの本当に ReAct か? といいたくが、何もせず動いて便利
createReactAgent({prompt, stateSchema}) 渡せる
State は Annotation を拡張して単に渡せば良い
code:extend.ts
const StateAnnotation = Annotation.Root({
...MessagesAnnotation.spec,
foo: Annotation<string>,
});
この状態はどう更新するねんというと Tool から Command で更新できる
new Command({ update: { foo: "foo" } })
状態を元にプロンプトを変える prompt に関数や runnbale を渡すようにする
code:prompt.ts
prompt: (state) => {
},
MCP 簡単に使う
$ npx @langchain/langgraph-cli dev
code:single.ts
import { ChatVertexAI } from "@langchain/google-vertexai";
import { MultiServerMCPClient } from "@langchain/mcp-adapters";
import { createReactAgent } from "@langchain/langgraph/prebuilt";
const model = new ChatVertexAI({
model: "gemini-2.5-flash-preview-05-20",
location: "us-central1",
authOptions: {
projectId: "pokutuna-playground",
},
});
const mcpClient = new MultiServerMCPClient({
throwOnLoadError: true,
prefixToolNameWithServerName: true,
additionalToolNamePrefix: "mcp",
useStandardContentBlocks: true,
mcpServers: {
playwright: {
command: "npx",
},
},
});
export const agent = createReactAgent({
llm: model,
tools: await mcpClient.getTools(),
});