メインコンテンツまでスキップ

Tool calling フローを実行する

Editor SDK の基本

Editor AI SDK は、パッケージに含まれている Editor SDK でドキュメントを開いて制御します。Thinkfree Office の iframe を接続したことがない場合は、 先に Editor SDK クイックスタートをお読みください。

最も手早く試せる完全なサンプルは Editor AI SDK Playground です。Thinkfree が提供するサンプル ドキュメントを開き、Editor SDK を Thinkfree Office の iframe に接続して、ドキュメントツールを小さな LLM ループに公開します。

npm で公開されている Editor AI SDK をプロジェクトディレクトリにインストールします。Editor SDK が含まれているため @thinkfree.dev/tfo-sdk を別途インストールする必要はなく、Office と createOfficeToolkit も @thinkfree.dev/tfo-ai-sdk から import します。

npm install @thinkfree.dev/tfo-ai-sdk

1. ドキュメントを開いて Editor SDK を接続する​

import { Office } from "@thinkfree.dev/tfo-ai-sdk";

const iframe = document.querySelector("#office-frame");
const word = Office.word(iframe); // Office.cell for Spreadsheet, Office.show for Presentation
await word.whenReady(); // wait until Office's SDK bridge answers

Office.word(iframe) は iframe.src から Thinkfree Office の origin を導出し、ワイルドカードは使用しません。whenReady() で Thinkfree Office のブリッジが応答するまで待機します。ドキュメントを開くことに失敗した状態では SDK の接続も完了しないため、まず iframe 内のエラーを確認します。

2. Thinkfree Office ツールキットを作成する​

import { createOfficeToolkit } from "@thinkfree.dev/tfo-ai-sdk";

const toolkit = await createOfficeToolkit(word, { provider: "anthropic", preset: "core", include: ["insert_text"] });
console.log(`${toolkit.tools.length} Office tools advertised`); // Anthropic Messages wire shape

createOfficeToolkit() は Thinkfree Office のツールカタログを読み取り、ループ用にまとめます。toolkit.tools はすでにプロバイダー API の 形式になっており、toolkit.systemPrompt はモジュールプロンプトにツール使用ルールを加えたものです。toolkit.dispatch(name, args) はツールを 実行し、ツール結果(ToolResult: { success, failure? })を返します。preset と include を使って、ツールセットを小さく、タスクに合ったものに保ってください。 ツールが少ないほど選択の品質が上がり、モデルの誤った判断による影響が小さくなります。

AI Agent が registerTool と unregisterTool を提供している場合は、Editor AI SDK の bridgeToolsViaSdk(word, modelContext) で Tool を登録し、返されたハンドルの unregisterAll() で登録を解除できます。許可する Tool を制限する連携の例は、Quickstart の Editor AI SDK セクションを参照してください。以下の chat-ui サンプルはツールキットを直接使用します。

3. スキーマの送信、呼び出しの実行、結果の返却​

以下の chat-ui サンプルは、Anthropic Messages 形式の content と stop_reason を使用します。

  1. ユーザーのリクエストと許可されたツールスキーマを createMessage() で送信します。
  2. assistant の応答全体を会話履歴に追加します。
  3. 各 tool_use の名前・引数・重複した呼び出し ID を検査し、ユーザーの承認を得ます。
  4. 承認されたツールを toolkit.dispatch() で実行し、同じ呼び出し ID を持つ tool_result をまとめて 1 つの user メッセージとして返します。
  5. モデルがツール呼び出しを終えたら終了します。実行は最大 8 ステップまでです。

toolkit.dispatch() は ToolResult で完了します。is_error: !result.success をモデルに渡し、失敗を成功として表示しないでください。 テキストを解析する代わりに result.failure.code(stale、invalid、permission、…)で分岐します。タイムアウトの後は、 ドキュメントに操作が反映されたかを確認してから再度リクエストします。すでに実行された編集は、ループが失敗したり上限に達したりしても自動的には元に戻りません。 失敗コードと低レベルの getTools() 経路については、ドキュメントツールとエラーを参照してください。

4. createMessage の実装: direct モード​

ステップ 3 は createMessage() を呼び出します。これは会話をモデルに送信する、アプリケーション側の関数です。ループを最も手早く動かす方法は direct モードで、ブラウザーがプロバイダー API を直接呼び出します。API_KEY と MODEL は、ユーザーのテストアカウントで用意したキーと利用可能なモデル ID です。以下のサンプルは Anthropic の direct 呼び出しで、 ステップ 3 で使用する正規化された { content, stop_reason } の形式を返します。

// Direct mode: the browser calls the provider API with your key - local testing only.
async function createMessage({ system, messages, tools }) {
const res = await fetch("https://api.anthropic.com/v1/messages", {
method: "POST",
headers: {
"content-type": "application/json",
"x-api-key": API_KEY, // visible to the page - never ship a key
"anthropic-version": "2023-06-01",
"anthropic-dangerous-direct-browser-access": "true", // local browser access
},
signal: AbortSignal.timeout(60000),
body: JSON.stringify({ model: MODEL, max_tokens: 8192, system, messages, tools }),
});
if (!res.ok) throw new Error(`Anthropic API error ${res.status}: ${await res.text()}`);
const data = await res.json();
return { content: data.content, stop_reason: data.stop_reason };
}

direct モードはバックエンドが不要なため、個人のワークステーションで手軽に使えます。ただし、キーがページやブラウザーの開発者ツールにそのまま 表示されるため、ローカルでのテストにのみ使用し、JavaScript や静的ファイルにキーを含めて配布しないでください。

本番環境ではリレーサーバーを使用する

プロバイダーのキーはバックエンドのリレーサーバーに置き、createMessage() がプロバイダー API の代わりにリレーサーバーを呼び出すように変更してください。 変わるのはリクエスト URL、ヘッダー、リクエスト本文の構造で、応答として受け取る { content, stop_reason } の形式と tool loop は そのままです。リレーサーバーの役割と実行方法、そしてこのサンプルに合わせた createMessage() の置き換え関数については リレーサーバーを、リクエスト/レスポンスのフィールドについては リレーサーバーのリクエスト/レスポンス仕様を参照してください。

5. 接続を解除する​

window.addEventListener("pagehide", () => word.disconnect());

disconnect() は SDK の接続のみを解除します。Thinkfree Office とドキュメントには影響しません。

期待される結果​

チャットに選択されたツールと結果が表示され、同じページのドキュメントに変更内容が反映されます。モデルが文章だけを返す場合は、ツールスキーマが プロバイダーの必須形式で送信されているか、プロンプトがツールの使用を明確に求めているかを確認してください。

chat-ui サンプルコード​

このサンプルでは、Word ドキュメントの末尾にテキストを追加する操作のみを許可します。選択範囲の置き換えや任意の位置での編集は公開しません。 モデルに送るスキーマをツールキットの insert_text の入力のうち text に限定し、実行直前に値とユーザーの承認を確認します。 保存は自動では実行されないため、ドキュメントで結果を確認してから保存します。

上記の npm インストールを完了したプロジェクトディレクトリに、以下のファイルを index.html として保存します。YOUR_OFFICE_DOCUMENT_OPEN_URL を Word の open URL に置き換えます。 プロジェクトディレクトリで python3 -m http.server 3000 --bind 127.0.0.1 を実行し、http://localhost:3000 を開きます。 画面でテスト用の API キーと、アカウントで利用可能なモデル ID を入力します。キーが入力された状態でこのファイルを共有しないでください。

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Editor AI SDK local example</title>
<script type="importmap">
{"imports":{"@thinkfree.dev/tfo-ai-sdk":"./node_modules/@thinkfree.dev/tfo-ai-sdk/dist/index.js"}}
</script>
<style>
body { font-family: system-ui, sans-serif; }
#office-frame { width: 100%; height: 600px; border: 0; }
#log { white-space: pre-wrap; }
</style>
</head>
<body>
<label>Test API key <input id="key" type="password" autocomplete="off" /></label>
<label>Model ID <input id="model" autocomplete="off" /></label>
<form id="composer">
<input id="prompt" aria-label="Request" placeholder="Append a short greeting" required />
<button id="send" disabled>Send</button>
</form>
<pre id="log" aria-live="polite"></pre>
<iframe id="office-frame" title="Thinkfree Office document" src="YOUR_OFFICE_DOCUMENT_OPEN_URL"></iframe>
<script type="module">
import { Office, createOfficeToolkit } from "@thinkfree.dev/tfo-ai-sdk";

const log = document.querySelector("#log");
const send = document.querySelector("#send");
const say = (text) => { log.textContent += text + "\n"; };
const word = Office.word(document.querySelector("#office-frame"));
let toolkit, tool, schema, busy = false;
try {
await word.whenReady();
toolkit = await createOfficeToolkit(word, { provider: "anthropic", preset: "core", include: ["insert_text"] });
[tool] = toolkit.tools; // Anthropic Messages shape: { name, description, input_schema }
if (!tool || tool.input_schema.properties?.text?.type !== "string") {
throw new Error("This Office version does not provide the expected insert_text tool.");
}
schema = {
type: "object",
properties: { text: { ...tool.input_schema.properties.text, minLength: 1, maxLength: 2000 } },
required: ["text"], additionalProperties: false,
};
send.disabled = false;
say("Ready. Each approved call appends text to the document.");
} catch (error) {
say("Connection failed. Check the document open URL and Office/SDK versions. " + error.message);
}

async function createMessage({ system, messages, tools }) {
const API_KEY = document.querySelector("#key").value.trim();
const MODEL = document.querySelector("#model").value.trim();
if (!API_KEY || !MODEL) throw new Error("Enter a test API key and an available model ID.");
const res = await fetch("https://api.anthropic.com/v1/messages", {
method: "POST",
headers: {
"content-type": "application/json",
"x-api-key": API_KEY,
"anthropic-version": "2023-06-01",
"anthropic-dangerous-direct-browser-access": "true",
},
signal: AbortSignal.timeout(60000),
body: JSON.stringify({ model: MODEL, max_tokens: 8192, system, messages, tools }),
});
if (!res.ok) throw new Error(`Model request failed (HTTP ${res.status}). Check the key, model and quota.`);
const data = await res.json();
if (!Array.isArray(data.content)) throw new Error("Invalid model response.");
return { content: data.content, stop_reason: data.stop_reason };
}

function validate(call) {
const args = call.input;
if (call.name !== tool.name || !args || typeof args !== "object" || Array.isArray(args)
|| Object.keys(args).length !== 1 || typeof args.text !== "string"
|| args.text.length < 1 || args.text.length > 2000) {
throw new Error("Only insert_text with 1–2000 characters of text is allowed.");
}
return args.text;
}

document.querySelector("#composer").addEventListener("submit", async (event) => {
event.preventDefault();
if (busy || !tool) return;
const prompt = document.querySelector("#prompt").value.trim();
if (!prompt) return;
busy = true;
send.disabled = true;
// A fresh conversation per submission avoids reusing an incomplete tool turn after an error.
const history = [{ role: "user", content: prompt }];
const seenCalls = new Set();
const definitions = [{ name: tool.name, description: "Append text to the document.", input_schema: schema }];
try {
for (let step = 0; step < 8; step++) {
const res = await createMessage({ system: toolkit.systemPrompt, messages: history, tools: definitions });
history.push({ role: "assistant", content: res.content });
for (const block of res.content) if (block.type === "text") say(block.text);
if (res.stop_reason !== "tool_use") { say("Finished. Review the document before saving."); return; }
const calls = res.content.filter((block) => block.type === "tool_use");
if (!calls.length) throw new Error("The model requested tools without a tool call.");
const results = [];
for (const call of calls) {
if (typeof call.id !== "string" || !call.id || seenCalls.has(call.id)) {
throw new Error("Missing or repeated tool call ID.");
}
seenCalls.add(call.id);
const text = validate(call);
if (!window.confirm("Append this text?\n\n" + text)) {
say("Cancelled. No further tools will run."); return;
}
const result = await toolkit.dispatch(tool.name, { text, insertAt: "end", replace: false });
say(result.success ? "Text append requested."
: `Tool failed (${result.failure.code}). Inspect the document before retrying.`);
results.push({ type: "tool_result", tool_use_id: call.id,
content: JSON.stringify(result), is_error: !result.success });
}
history.push({ role: "user", content: results });
}
say("Stopped at the 8-step limit. Review any edits already made before sending another request.");
} catch (error) {
say(error.message + " Existing edits are not rolled back. Check the document before retrying.");
} finally {
busy = false;
send.disabled = false;
}
});
window.addEventListener("pagehide", () => word.disconnect());
</script>
</body>
</html>

API キーまたはモデル ID がない場合、モデルリクエストは送信されません。HTTP 401 の場合はキーを、429 の場合はプロバイダーの上限を確認します。 ドキュメントの接続に失敗した場合は、まず iframe 内のオープンエラーを解決します。承認のキャンセル、ツールのエラー、タイムアウトの後は、ドキュメントを確認し、 必要な操作だけを再度リクエストします。実際のサービスでは、独自の認証、ドキュメントの権限確認、リレーサーバーが必要です。