본문으로 건너뛰기

자체 채팅 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 요구 사항을 참고하십시오. attachDocument()가 Editor SDK 연결과 Thinkfree Office 준비 대기를 대신하므로 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

패키지 하나만 설치합니다. Editor SDK가 함께 설치되고 각 진입점 번들에 포함되므로 import map에는 /headless 진입점 하나만 적으면 됩니다.

<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, 오른쪽에 자체 채팅을 둔 페이지입니다. 두 파일을 저장하고 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는 한 턴에서 허용하는 도구 호출 횟수입니다(기본 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이 대화 하나입니다. 보내기는 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()은 런타임의 도구 호출 시작·결과 이벤트를 하나로 합치고 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)로 분기하십시오. 문서 도구 및 오류를 참고하십시오.