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

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

始める前に

アプリケーションのページがチャット UI を表示し(Thinkfree Office サーバーが提供する iframe、またはページにマウントするコンポーネント)、 @thinkfree.dev/tfo-ai-sdk/chat-ui の createChatUiBridge() で駆動します。ドキュメントツールは引き続き Thinkfree Office ツールキットから提供されます。先にクイックスタートを完了してください。

独自のループを使用しない場合

@thinkfree.dev/tfo-ai-sdk/chat の mountChat() は、チャット UI、Thinkfree エージェントループ、そして両者をつなぐ接続部分を一度にマウントします。 このページは、独自のループとモデルがユーザーに応答する場合に使用します。

Thinkfree チャット UI は、進行状況チップ、通知カード、選択の要求、編集計画の承認、添付ファイルを提供します。チャット UI ブリッジを使うと、この UI をそのまま 活かし、ツールループとモデル接続の 2 つだけを用意すれば済みます。ブリッジはチャット UI ツール 8 種をモデルに公開し、モデルの出力を UI に レンダリングし、ユーザーの操作(選択・承認・停止)をループに返します。

構成要素提供元
チャット UI(Thinkfree Office サーバーが提供、またはページ内の /ui コンポーネント)Thinkfree
ドキュメントツール、プロンプトルール、ToolResultThinkfree Office ツールキット(@thinkfree.dev/tfo-ai-sdk ルートエントリー)
チャット UI ツール、プロンプトルール、turn 状態、ハンドシェイクチャット UI ブリッジ(@thinkfree.dev/tfo-ai-sdk/chat-ui)
ツールループ、モデル接続、リレーアプリケーション

1. チャット UI を external モードで読み込む​

Thinkfree Office サーバーのチャット UI ページを mode=external で iframe に表示します。このモードでは、ページは UI のみをレンダリングし、独自のエージェントを 起動する代わりにアプリケーション側のウィンドウと通信します。

<iframe id="chat-frame" title="Thinkfree chat UI"
src="https://office.example.com/webword/commonFrame/js/addIn/tfoAiAssistant/index.html?mode=external&brainOrigin=https%3A%2F%2Fapp.example.com&module=word&lang=en"></iframe>
クエリパラメーター必須意味
mode=externalはいUI のみをレンダリングします。エージェントはこの iframe の外にあります
brainOriginはいブリッジを作成するページ(アプリケーションのページ)の正確な origin。* は拒否されます
brainWindow=openerいいえwindow.open() で UI を開いた場合、window.parent の代わりに window.opener に送信します
moduleいいえword、cell、show - 開始画面とクイックアクションを選択します
langいいえUI の言語。例: ko_KR、en

または、チャット UI をページにマウントする​

0.4.0 以降、チャット UI はコンポーネントとしても提供されます。@thinkfree.dev/tfo-ai-sdk/ui の mountChatUi() はページの要素内に UI を描画するため(シャドウ DOM、React 同梱、iframe なし)、ページのスタイルと UI が互いに影響しません。この場合、UI とブリッジは同じ ウィンドウを使用するため、ステップ 2 で iframeEl の代わりに peerWindow: window を渡します。

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

const ui = mountChatUi(document.querySelector("#chat"), { locale: "en", module: "word" });
// step 2: createChatUiBridge({ peerWindow: window, ... })
// cleanup: chat.destroy(); ui.unmount();

フォントはバンドルに含まれません。fontBase(Pretendard の woff2 ファイルがあるディレクトリ)を渡すか、ページのフォントを使用します。

2. ブリッジを作成する​

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

const toolkit = await createOfficeToolkit(word, { provider: "anthropic", preset: "core" });
const chatFrame = document.querySelector("#chat-frame");

const chat = createChatUiBridge({
iframeEl: chatFrame, // window and exact origin derived from the iframe src
provider: "anthropic", // same wire shape as toolkit.tools
language: { code: "en", name: "English" }, // language named in the prompt rules
listTools: () => toolkit.catalog, // answers the "/tools" command locally
onUserInput: runTurn, // your loop - see step 3
onAbort: () => console.log("user pressed stop"),
onSettingsChange: (settings, ctx) => { /* ctx.systemPrompt changed; use it on the next turn */ },
});
ハンドルのメンバー用途
chat.toolsプロバイダー API 形式のチャット UI ツール 8 種。toolkit.tools と一緒に送信します
chat.systemPromptチャット UI ツールのルール(編集承認モードまたは自動進行モード、開発者モード)。toolkit.systemPrompt の後に付加します
chat.handles(name)ツール呼び出しがチャット UI のものであれば true。その呼び出しは chat.dispatch に、それ以外は toolkit.dispatch に送ります
chat.dispatch(name, args)チャット UI ツールを実行し、ToolResult で完了します。対話型カードはユーザーが応答した時点で完了します
chat.notify(text)モデルの最終テキストをカードとしてレンダリングします。この turn ですでにカードで報告済みの場合は省略されます
chat.settings現在のアシスタント設定: mode(edit-accept または auto-proceed)と developerMode
chat.destroy()リスナーを削除し、待機中のカードを閉じます

3. ユーザー入力ごとにループを実行する​

onUserInput は、ユーザーが送信したテキストと添付ファイル、そして turn コンテキストを受け取ります。モデルの最終テキストを返すとブリッジが レンダリングし、例外をスローするとエラーカードを表示します。ユーザーが停止を押すと turn.signal が abort されます。

async function runTurn({ text, attachments }, turn) {
const system = `${toolkit.systemPrompt}\n\n${chat.systemPrompt}`;
const tools = [...toolkit.tools, ...chat.tools];
const history = [{ role: "user", content: text }];
for (let step = 0; step < 12; step++) {
if (turn.signal.aborted) return "";
const res = await createMessage({ system, messages: history, tools }); // see the quickstart
history.push({ role: "assistant", content: res.content });
if (res.stop_reason !== "tool_use") {
return res.content.filter((b) => b.type === "text").map((b) => b.text).join("\n");
}
const results = [];
for (const call of res.content.filter((b) => b.type === "tool_use")) {
const result = chat.handles(call.name)
? await chat.dispatch(call.name, call.input)
: await toolkit.dispatch(call.name, call.input);
results.push({ type: "tool_result", tool_use_id: call.id,
content: JSON.stringify(result), is_error: !result.success });
}
history.push({ role: "user", content: results });
}
return "";
}

2 つの dispatch 関数はどちらも ToolResult を返すため、モデルはドキュメントツールとチャット UI ツールから同じ形式の結果を読み取ります。モデルが show_request_input や show_edit_plan_list を呼び出すと、chat.dispatch はユーザーが選択・承認・閉じる操作をするまで待機し、 結果テキストで何が起きたかをモデルに伝えます。編集承認モード(既定)では、プロンプトルールがモデルに対し、ドキュメントツールを 呼び出す前に編集計画を提示して承認を待つよう指示するため、この経路のためにループ側で承認ステップを別途追加する必要はありません。

4. ハンドシェイクとライフサイクル​

  • ハンドシェイク。 ブリッジは作成時に tfo-ai:hello を送信し、UI はプロトコルバージョンを含む tfo-ai:ready で応答します。UI は 読み込み時にも ready を送信します。どちらが先に起動してもかまいません。ready より前にブリッジが送信したメッセージはキューに入ります。バージョンが異なる場合は、 UI がエラーカードを表示し、ブリッジは停止して onProtocolMismatch が呼び出されます。
  • turn 状態。 ブリッジは onUserInput の開始時に turn を進行中、終了時に完了としてマークします。その間、UI は停止ボタンを 表示し、追加の入力をキューに入れます。
  • 停止。 ユーザーによる停止は turn.signal を abort して onAbort を呼び出し、待機中のカードを閉じて保留中の chat.dispatch 呼び出しを完了させます。停止後に届いた結果やエラーは破棄されます。
  • 設定。 ユーザーが UI でアシスタント設定を変更すると、onSettingsChange(settings, { systemPrompt, notice }) が呼び出されます。新しい systemPrompt は次の turn から使用し、notice はモデルが変更に気付けるよう会話に挿入できる短いメッセージです。UI はこの設定を自ら保存し、ready メッセージに含めて送信します。ブリッジの設定と異なる場合はブリッジがその値を採用し、onReady の前に initial: true を付けて onSettingsChange を呼び出すため、ループ側で設定を保存する必要はありません。
  • クリーンアップ。 iframe を削除するときは chat.destroy() を呼び出します。

プロトコルリファレンス (v1)​

すべてのメッセージは、双方とも正確な origin を指定した window.postMessage({ type, payload }, origin) です。

メッセージ方向ペイロード
tfo-ai:readyUI → ブリッジ{ protocolVersion: 1, capabilities?: string[] }
tfo-ai:helloブリッジ → UI{ protocolVersion: 1 }
tfo-ai:user-inputUI → ブリッジ{ text, attachments?: [{ fileName, mimeType, size, base64 }] }
tfo-ai:user-actionUI → ブリッジ{ componentId, action: "select" | "select-custom" | "accept-all" | "close", value? }
tfo-ai:set-assistant-settingsUI → ブリッジ{ settings: { mode, developerMode } }
tfo-ai:abort-turn,
tfo-ai:clear-conversation
UI → ブリッジなし
tfo-ai:component-add /
-update / -remove
ブリッジ → UI{ id, kind, data } / { id, data } / { id }
tfo-ai:turn-stateブリッジ → UI{ inProgress }
tfo-ai:trigger-inputブリッジ → UI{ text } - ユーザーが入力したかのように発話を挿入します

コンポーネントの種類は progress-status、notification、request-input、edit-plan-list、tool-call-info で、チャット UI ツール (show_progress_status、update_progress_status、show_notification、show_request_input、show_edit_plan_list、 update_edit_plan_list、show_tool_call_info、remove_component)がこれらを作成します。コンポーネントメッセージを直接送信する必要は ありません。モデルがチャット UI ツールを呼び出すと、ブリッジが送信します。

このリリースでの制限​

  • 添付ファイルは base64 で onUserInput に渡され、ブリッジがどこかにアップロードすることはありません。テキストや画像の添付は実用的ですが、Thinkfree Office のバイナリ添付ファイル(例: .pptx)は external モードではブリッジされません。
  • external モードのチャット UI ページは Thinkfree Office サーバーが提供するため、そこから読み込む必要があります。独自のドメインで UI を表示するには、/ui コンポーネントをマウントします。
  • プロンプトルールは韓国語で記述されており、その中で UI の言語が指定されます。モデルはユーザーの言語で応答します。