コンテンツにスキップ

LangGraph

LangGraph のエージェントは、ほかのことと同じく、ツールを通して API に支払います。そのツールが spendctl サイドカー経由で取得するようにすれば、支払いのルールはグラフが抱える問題ではなくなります。エージェントは鍵を持たず、拒否は、モデルが次の行動を決められる文章で返ります。

サイドカーを起動します。初めて試すときは、モックの売り手も起動してください(クイックスタート)。

ターミナルウィンドウ
npx spendctl init
npx spendctl mock # ターミナル 1
npx spendctl start # ターミナル 2
ターミナルウィンドウ
npm install @langchain/langgraph @langchain/core @langchain/anthropic @spendctl/client zod

AgentClient は、名前を付けた 1 つのエージェントとして、http://127.0.0.1:8402(または SPENDCTL_URL)のサイドカーと通信します。readRefusal は、spendctl が支払わなかったときにその理由を返し、支払い済みか無料の呼び出しなら undefined を返します。

import { ChatAnthropic } from "@langchain/anthropic";
import { tool } from "@langchain/core/tools";
import { createReactAgent } from "@langchain/langgraph/prebuilt";
import { AgentClient, readRefusal } from "@spendctl/client";
import { z } from "zod";
const spendctl = new AgentClient({ agent: "researcher" });
const fetchPaid = tool(
async ({ url }) => {
const response = await spendctl.fetch(url);
const refusal = await readRefusal(response);
return refusal ? `Not paid: ${refusal.message}` : await response.text();
},
{
name: "fetch_paid_url",
description: "GET a URL that may charge per request (HTTP 402). Budget and approvals are enforced by spendctl.",
schema: z.object({ url: z.string().url() }),
},
);
const checkBudget = tool(async () => JSON.stringify(await spendctl.budget()), {
name: "check_budget",
description: "Remaining spend for this agent.",
schema: z.object({}),
});
const agent = createReactAgent({
llm: new ChatAnthropic({ model: "claude-sonnet-5-5" }),
tools: [fetchPaid, checkBudget],
});
const result = await agent.invoke({
messages: [
{
role: "user",
content: "Check my budget, then get the weather in Tokyo from http://localhost:4021/weather?city=Tokyo",
},
],
});
console.log(result.messages.at(-1)?.content);
  • 支払い済み:売り手の応答本文です。金額と台帳の ID は応答ヘッダ x-spendctl-amount と x-spendctl-attempt に入っているので、必要ならそのまま渡せます。
  • 拒否:Not paid: に続けて spendctl の文が入ります。たとえば、ホストが許可リストにない、1 日の予算を使い切った、といった内容です。これをツールの結果として返すと、モデルは拒否の理由を説明したり、計画を変えたりできます。
  • 人間の判断待ちで保留:既定の approvals.hold: true では、誰かが spendctl approve を実行するまでツール呼び出しが待ちます(最長 holdMax、4 分)。グラフ側にタイムアウトがある場合は approvals.hold: false にして、ツールが承認 ID をすぐ返すようにし、エージェントにはそれを報告させるか、あとで戻って来させてください(承認フロー)。

役割ごとにエージェント名を 1 つ

Section titled “役割ごとにエージェント名を 1 つ”

予算はエージェント名に紐づきます。グラフ内の役割ごとに別々の AgentClient({ agent: "…" }) を用意し、spendctl.yaml の agents: にもそれぞれの項目を作ってください。こうすると、調査役と購入役が互いの予算を使うことはできません。Free で使えるエージェントは 2 つです(プランとライセンスキー)。