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

独自のチャット UI で Thinkfree エージェントループを使用する

連携方法 3

ページは独自のチャット UI をそのまま使用し、@thinkfree.dev/tfo-ai-sdk/headless の Thinkfree エージェントループがモデルを呼び出して ドキュメントツールを実行します。他の方法との比較は連携方法を選ぶを参照してください。

ヘッドレスエージェントは、Thinkfree Office に組み込まれた AI Agent 内で動作するものと同じエージェントループから、UI だけを取り除いたものです。Thinkfree Office の ドキュメントツールをモデルに公開し、モデルが選んだツールをブラウザー内の Editor SDK で実行し、モデルが応答するまでこれを 繰り返します。アプリケーションが作るのはチャット UI だけです。メッセージ一覧と入力欄がエージェントの session にテキストを送信し、応答を 描画すれば完了です。

モデルがドキュメントに直接触れることはありません。モデルはツールを選ぶだけで、実行はブラウザー内の Editor SDK が行います。リレーサーバーはモデルリクエストを転送し、このリクエストにはツールが読み取ったドキュメントの内容が含まれる場合があります。リレーがドキュメントを直接開いたり編集したりすることはありません。

始める前に​

  • ドキュメントのオープン URL。ドキュメント URL と iframe の要件を 参照してください。Editor SDK の接続と Thinkfree Office の準備完了待ちは attachDocument() が代行するため、Office.word() や whenReady() を 直接呼び出す必要はありません。Thinkfree Office に組み込まれた AI Agent パネルが独自のチャットの横に一緒に表示されないよう、オープン URL に hideContentBar=1 を 付けてください。
  • モデルの接続。既定では、エージェントは Thinkfree Office の管理者 AI Provider 設定をそのまま使用するため、ページにキーやエンドポイントは現れ ません。ページ側でモデルを指定するにはリレーサーバーを使用し、プロバイダーの API キーはローカルでのテストにのみ 使用してください。
  • Node.js と npm、そしてサンプルページを配信するローカルの静的サーバー。

インストール​

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

インストールするパッケージは 1 つだけです。Editor SDK も一緒にインストールされ、各エントリーポイントのバンドルに含まれるため、import map には /headless エントリーポイント 1 つだけを記述すれば済みます。

<script type="importmap">
{ "imports": {
"@thinkfree.dev/tfo-ai-sdk/headless": "./node_modules/@thinkfree.dev/tfo-ai-sdk/dist/headless.js"
} }
</script>
エントリーポイント内容
@thinkfree.dev/tfo-ai-sdk/headlessmountHeadless()、getProviderCatalog()。エージェントランタイムを含み、UI はありません。このページで使用
@thinkfree.dev/tfo-ai-sdk/chat-uiThinkfree チャット UI を独自のループとつなぐチャット UI ブリッジ(方法 2)
@thinkfree.dev/tfo-ai-sdk/ui、/chatThinkfree チャット UI コンポーネントと、それをこのエージェントと組み合わせる mountChat()(方法 4)

サンプルページ​

左に Thinkfree Office、右に独自のチャットを配置したページです。2 つのファイルを保存し、YOUR_OFFICE_DOCUMENT_OPEN_URL を置き換えてから、ローカルの 静的サーバーでフォルダーを配信してください。

chat.html

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Headless agent with my chat UI</title>
<script type="importmap">
{ "imports": { "@thinkfree.dev/tfo-ai-sdk/headless": "./node_modules/@thinkfree.dev/tfo-ai-sdk/dist/headless.js" } }
</script>
<style>
html, body { height: 100%; margin: 0; font: 14px/1.5 system-ui, sans-serif; }
body { display: grid; grid-template-columns: 1fr 380px; }
#editor { width: 100%; height: 100%; border: 0; }
#chat { display: grid; grid-template-rows: auto 1fr auto; border-left: 1px solid #ddd; min-height: 0; }
#chat header { padding: 8px 12px; border-bottom: 1px solid #ddd; color: #555; }
#messages { overflow: auto; padding: 10px 12px; }
.msg { margin: 0 0 10px; white-space: pre-wrap; }
.msg.user { color: #1f5fbf; }
.msg.tool { font: 12px/1.4 monospace; color: #666; }
.msg.error { color: #b00020; }
form { display: flex; gap: 6px; padding: 10px 12px; border-top: 1px solid #ddd; }
textarea { flex: 1; resize: none; height: 56px; }
</style>
</head>
<body>
<!-- Office. chat.js sets src to the open URL -->
<iframe id="editor" title="Thinkfree Office document"></iframe>

<!-- Your own chat UI: a message list and an input box -->
<section id="chat">
<header id="status">Preparing…</header>
<div id="messages"></div>
<form id="composer">
<textarea id="prompt" placeholder="Add the heading 'Quarterly summary' at the top" disabled></textarea>
<button type="submit" disabled>Send</button>
</form>
</section>

<script type="module" src="./chat.js"></script>
</body>
</html>

chat.js

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

// Open URL issued by your Office/storage integration, and the module that matches it
const OPEN_URL = "YOUR_OFFICE_DOCUMENT_OPEN_URL";
const MODULE = "word"; // "word" | "cell" | "show"

// "office": read Office's admin AI Provider settings when the document connects
const AI = "office";

const $status = document.getElementById("status");
const $messages = document.getElementById("messages");
const $form = document.getElementById("composer");
const $prompt = document.getElementById("prompt");
const $send = $form.querySelector("button");
function say(kind, text) {
const el = document.createElement("div");
el.className = "msg " + kind;
el.textContent = text;
$messages.appendChild(el);
$messages.scrollTop = $messages.scrollHeight;
}

// 1. Open Office. hideContentBar=1 hides Office's built-in AI Agent panel
const iframe = document.getElementById("editor");
const url = new URL(OPEN_URL);
url.searchParams.set("hideContentBar", "1");
iframe.src = url.toString();

// 2. Mount the agent. The document is in a child iframe, so connect it later with attachDocument
const agent = mountHeadless({
transport: { kind: "iframe" },
aiProviderConfig: AI,
systemPrompt: "You help the user edit the open document. Prefer tools over prose. Reply in the user's language.",
});

// 3. Show tool calls. The event already carries the parsed ToolResult
agent.onToolCall((e) => {
if (e.phase === "start") { say("tool", "⚙ " + e.name + " " + JSON.stringify(e.args)); return; }
const summary = e.result
? JSON.stringify(e.result.success ? e.result.data ?? "" : e.result.failure)
: JSON.stringify(e.raw);
say("tool", (e.success ? "✓ " : "✕ ") + e.name + " " + summary.slice(0, 200));
});

// 4. When Office has loaded, connect the document and register its tools
iframe.addEventListener("load", async () => {
try {
const toolNames = await agent.attachDocument({ iframeEl: iframe, module: MODULE });
$status.textContent = `Connected · ${toolNames.length} document tools`;
$prompt.disabled = false; $send.disabled = false; $prompt.focus();
} catch (err) {
$status.textContent = "Connection failed";
say("error", `${err.code ?? ""} ${err.message}`);
}
}, { once: true });

// 5. User input -> session.send -> final answer
$form.addEventListener("submit", async (ev) => {
ev.preventDefault();
const text = $prompt.value.trim();
if (!text) return;
$prompt.value = "";
say("user", text);
$send.disabled = true;
try {
const result = await agent.session.send(text); // resolves after the tool calls finish
if (result?.text) say("assistant", result.text);
} catch (err) {
say("error", String(err?.message ?? err));
} finally {
$send.disabled = false; $prompt.focus();
}
});

// 6. Clean up: unregister tools, disconnect Editor SDK, dispose the runtime
window.addEventListener("pagehide", () => agent.destroy());

期待される結果: ステータス行にドキュメントツールの数が表示されます。「Add the heading 'Quarterly summary' at the top」のように 依頼すると、チャットに ⚙ insert_paragraph のようなツール呼び出しと ✓ の結果が表示され、ドキュメントに見出しが追加された後、 モデルが応答します。

モデルの接続​

aiProviderConfig は、エージェントがモデルを呼び出す方法です。既定値 "office" は Thinkfree Office の管理者設定に従い、オブジェクトを 渡すとページ側で指定します。本番運用には "office" または relay を使用し、direct は個人の作業環境でのみ使用してください。

"office"relaydirect
フロードキュメント接続時に管理者設定(リレーのアドレス、プロバイダー、モデル)を読み取るブラウザー → 独自のリレーサーバー → プロバイダーブラウザー → プロバイダー API
キーの場所サーバーサーバーページ内。開発者ツールで見える
用途本番運用の既定。管理者による変更に追従するThinkfree Office の設定とは異なるモデルローカルでのテスト
// office (default): follow Office's admin AI Provider settings; re-read on every attachDocument
const AI = "office";

// relay: your relay server holds the key
const AI = {
connectionMode: "relay",
aiProvider: "google", // must match the provider in the admin settings when you use the Office relay
model: "YOUR_MODEL_ID",
relayRequest: { endpoint: "https://relay.example.com/ai-agent/relay", method: "POST" },
maxToolIterations: 20,
};

// direct: local tests only, the key is visible to the page
const AI = {
connectionMode: "direct",
aiProvider: "google", // "google" | "claude" | "openai" | "openai-compatible"
model: "YOUR_MODEL_ID",
auth: { kind: "apiKey", apiKey: "YOUR_TEST_API_KEY", exposeToEvents: false },
maxToolIterations: 20,
};
  • maxToolIterations は、1 つのターンで許可するツール呼び出しの回数です(既定は 100)。一般的な編集では 10~30 に設定してください。
  • relayRequest.method は POST のみ使用できます。
  • 社内 LLM のような OpenAI 互換サーバーは、aiProvider: "openai-compatible" と openAiCompatible: { preset: "custom", endpoint: "http://host:port/v1", path: "chat/completions" } で指定します。キーが 不要なサーバーでは auth を省略します。
  • Thinkfree Office とともに配布されるリレー(<Office origin>/ai-agent/relay)を使用する場合、キーとモデルは管理者設定に従い、 aiProvider はその設定と一致している必要があります。この場合は "office" を使う方が簡単です。
direct モードのキーはページに露出します

プロバイダーのキーを JavaScript や静的ファイルに含めて配布しないでください。共有環境では常にリレーを使用します。

エージェントのマウントとドキュメントの接続​

const agent = mountHeadless({
transport: { kind: "iframe" }, // the document is in a child iframe -> attachDocument
aiProviderConfig: AI,
systemPrompt: "…", // optional; appended after the module prompt and toolkit rules
// preset: "core", // optional; default "full". "core" leaves out execute_script
});

const toolNames = await agent.attachDocument({
iframeEl: iframe,
module: "word", // "word" | "cell" | "show"
// frameworkOrigin: "https://…", // only when the origin cannot be derived from iframe.src
});
  • mountHeadless() は同期関数です。ランタイム、セッション、modelContext を作成しますが、この時点ではまだドキュメントを認識していません。オプションは transport(必須)、aiProviderConfig、systemPrompt、preset、sessionId、sdkTimeoutMs(既定は 5,000ms)、 readyTimeoutMs(既定は 60,000ms)です。
  • ハンドルには session、modelContext、runtime、toolsReady、registeredToolCount、attachDocument() と detachDocument()(iframe transport の場合のみ)、onToolCall()、abortTurn()、destroy() があります。
  • attachDocument() は Editor SDK を Thinkfree Office に接続し(whenReady() を含む)、そのモジュールのドキュメントツールを登録した後、ツール名の 一覧で resolve します。"office" の場合は、このときに管理者設定も読み取ります。iframe の load イベントの後に呼び出してください。
  • 別のドキュメントを開くには、detachDocument() の後に iframe の src を変更し、再度 attachDocument() を呼び出します。
  • ツールは Thinkfree Office ツールキットを介して登録されます。モデルは呼び出しごとに ToolResult を 受け取り、モジュールプロンプトとツールキットのルールはシステムプロンプトに自動的に含まれます。
  • ドキュメントが子 iframe ではなく同じウィンドウや親ウィンドウにある場合は、 transport: { kind: "targetWindow", window, frameworkOrigin, module } でマウントします。マウント時にすぐ接続されるため、 attachDocument() の代わりに agent.toolsReady を待機します。

メッセージの送信とツール呼び出しイベントの受信​

agent.session が 1 つの会話です。送信は send()、ツール呼び出しイベントは agent.onToolCall()、キャンセルは agent.abortTurn() です。

const result = await agent.session.send("Add the heading 'Quarterly summary' at the top");
result.text; // the model's final answer (may be empty)
result.toolCalls; // tools run in this turn

const off = agent.onToolCall((e) => {
e.phase; // "start" | "result"
e.name; e.args; e.toolCallId;
e.success; // result phase: includes ToolResult failures
e.result; // result phase: ToolResult { success, data | failure: { code, message } }
e.raw; // result phase: the raw MCP result from the runtime
e.error; // result phase: failure reason
});
off(); // unsubscribe

agent.abortTurn(); // cancel the model request in progress; a tool already running is not stopped
  • send() は、モデル呼び出し → ツール実行 → モデル呼び出しを maxToolIterations の範囲内で繰り返し、モデルがツールを使わずに応答すると終了します。 応答が完了するまで新しいメッセージを送信できないよう、入力欄を無効にしておいてください。
  • 会話履歴はセッションが保持します。新しく始めるには、エージェントを destroy() して再度マウントするか、新しい sessionId で マウントします。
  • onToolCall() は、ランタイムのツール呼び出し開始・結果イベントを 1 つにまとめ、ToolResult を解析して渡します。代わりに session.on() でランタイムイベントを直接受け取る場合、結果は MCP 形式で、ToolResult の JSON はテキストブロック内にあります。

独自のツールと指示の追加​

ドキュメントツールと並べて、ページ上で実行されるツールを登録できます。たとえば、独自のストレージにあるドキュメントを開くツールです。ツール 一覧はターンが始まるたびに再読み込みされるため、いつ登録しても次のターンから使用されます。

agent.modelContext.registerTool({
name: "open_document",
description: "Open a document by URL in the Office pane.",
inputSchema: { type: "object", properties: { url: { type: "string" } }, required: ["url"] },
async execute({ url }) {
agent.detachDocument();
iframe.src = String(url);
await new Promise((r) => iframe.addEventListener("load", r, { once: true }));
await agent.attachDocument({ iframeEl: iframe, module: "word" });
return { content: [{ type: "text", text: "Document opened." }] };
},
});

systemPrompt は、モジュールプロンプトとツールキットのルールの後に付加されます。応答の言語、口調、禁止事項など、サービス固有のルールを記述してください。 ドキュメントツールの使い方はツールキットのルールにすでに含まれています。

クリーンアップとルール​

window.addEventListener("pagehide", () => agent.destroy());
  • destroy() は冪等です。ツールの登録を解除し、Editor SDK の接続を切断して、ランタイムをクリーンアップします。Thinkfree Office とドキュメントには影響 しません。
  • モデルは、プロンプト、会話履歴、ツールスキーマ、そしてツールが読み取ったドキュメントの内容を含むツール結果を受け取ります。ブラウザーの外に 出してよいものを決めてください。安全性ガイドを参照してください。
  • ツールセットは小さく保ってください。preset: "core" や絞り込んだ登録によって、誤った選択を減らし、応答を速くできます。
  • ターンが失敗したり abortTurn() を呼び出したりしても、すでに適用された編集は元に戻りません。影響の大きい操作は、実行前にユーザーの 確認を得てください。

トラブルシューティング​

症状確認事項
TIMEOUT で「Connection failed」になるオープン URL ではないか、Thinkfree Office が iframe の src とは異なる origin で読み込まれています。ドキュメント URL を参照してください。
ドキュメントツールが 0 個module の値がドキュメントの種類(オープン URL の app=)と異なるか、Thinkfree Office のビルドがそのモジュールのツールを公開していません。
最初の送信でプロバイダーエラーが発生する"office" を指定しているのに、Thinkfree Office に管理者 AI Provider 設定がありません(コンソールに警告)。オブジェクトの場合は、connectionMode、aiProvider、model のいずれかが空です。direct には auth.apiKey、relay には relayRequest.endpoint が必要です。
リレーへのリクエストが CORS でブロックされるリレーがページの origin を許可する必要があります。OPTIONS 応答の Access-Control-Allow-Origin を確認してください。
モデルがツールを使わずに言葉だけで応答するリクエストがあいまいか、ツールが多すぎます。具体的に依頼し、preset: "core" を試してください。
同じツールを繰り返してターンが止まるmaxToolIterations の上限に達しています。リクエストを分割するか、より大きなモデルを使用してください。
ツール結果が ✕ になるfailure.code(stale、invalid、permission、capability、no-op、internal)で分岐してください。ドキュメントツールとエラーを参照してください。