호출 한 번으로 Thinkfree 채팅 UI와 에이전트를 페이지에 두기
채팅 UI도 루프도 만들지 않습니다. @thinkfree.dev/tfo-ai-sdk/chat의 mountChat()이 페이지의 요소 안에 Thinkfree 채팅
UI를 그리고, 에이전트를 만들고, Thinkfree Office의 문서 도구를 연결합니다. 다른 방법과의 비교는
연동 방법 고르기를 참고하십시오.
Thinkfree Office 안에서 도는 것과 같은 채팅(진행 칩, 편집 계획 승인, 알림 카드, /tools 명령)을 레이아웃의 원하는 자리에
둡니다. 모델은 기본적으로 Thinkfree Office의 관리자 AI Provider 설정을 따르고, 페이지가 정할 수도 있습니다.
mountChat()은 따로도 쓸 수 있는 세 층을 조립합니다. 채팅 UI 컴포넌트(/ui의 mountChatUi()), 연결(/chat-ui의
attachSession()), 에이전트(/headless의 mountHeadless(), 헤드리스 에이전트 참고)입니다.
핸들이 세 층을 모두 노출하므로 필요하면 각 층의 API로 조정할 수 있습니다.
| 방법 2 | 방법 3 | 방법 4 (이 페이지) | |
|---|---|---|---|
| 채팅 UI | Thinkfree | 직접 만듦 | Thinkfree |
| 루프 | 직접 만듦 | Thinkfree | Thinkfree |
| 작성할 코드 | 루프 | 채팅 UI | 호출 한 번 |
모델은 문서에 직접 손대지 않습니다. 도구를 고르기만 하고, 실행은 에이전트가 브라우저 안의 Editor SDK로 합니다. 릴레이 서버는 모델 요청을 전달하며, 이 요청에는 도구가 읽은 문서 내용이 포함될 수 있습니다. 릴레이는 문서를 직접 열거나 편집하지 않습니다.
시작하기 전에
- 문서의 열기 URL. 문서 URL과 iframe 요구 사항을
참고하십시오.
mountChat()이 Editor SDK 연결과 Thinkfree Office 준비 대기를 대신합니다. Thinkfree Office에 내장된 AI Agent 패널이 이 채팅 옆에 함께 뜨지 않도록 열기 URL에hideContentBar=1을 붙이십시오. - 모델. 기본적으로 Thinkfree Office의 관리자 AI Provider 설정을 쓰므로 따로 준비할 것이 없습니다. 다른 모델을 쓰려면 모델 연결에 있는 relay 또는 direct 설정을 넘깁니다.
- Node.js와 npm, 그리고 예제 페이지를 띄울 로컬 정적 서버.
설치
npm install @thinkfree.dev/tfo-ai-sdk
/chat 진입점에는 채팅 UI, 연결, 에이전트, Editor SDK 문서 API가 하나의 자립 번들(약 1.7MB)로 들어 있습니다. 번들러
없이 쓸 때 import map도 한 줄입니다. node_modules를 그대로 서빙하지 않고 번들 파일을 복사해 쓰면
apiReference.generated.js를 옆에 함께 두십시오.
<script type="importmap">
{ "imports": { "@thinkfree.dev/tfo-ai-sdk/chat": "./node_modules/@thinkfree.dev/tfo-ai-sdk/dist/chat.js" } }
</script>
/headless나 /ui를 따로 import하지 마십시오/chat이 둘을 이미 담고 있어 런타임이 두 번 로드됩니다. 대신 mountChat() 핸들의 ui, agent, session을
사용하십시오.
예제 페이지
왼쪽에 Thinkfree Office, 오른쪽에 채팅을 둔 페이지입니다. 두 파일을 저장하고 YOUR_OFFICE_DOCUMENT_OPEN_URL을 바꾼 뒤 로컬 정적
서버로 폴더를 띄우십시오.
chat-mount.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>mountChat: Thinkfree chat UI and agent in my page</title>
<script type="importmap">
{ "imports": { "@thinkfree.dev/tfo-ai-sdk/chat": "./node_modules/@thinkfree.dev/tfo-ai-sdk/dist/chat.js" } }
</script>
<style>
html, body { height: 100%; margin: 0; font: 14px/1.5 system-ui, sans-serif; }
body { display: grid; grid-template-columns: 1fr 420px; }
iframe { width: 100%; height: 100%; border: 0; }
#side { display: grid; grid-template-rows: auto 1fr; border-left: 1px solid #ddd; min-height: 0; }
#status { padding: 6px 12px; border-bottom: 1px solid #ddd; color: #555; font-size: 12.5px; }
#chat { min-height: 0; }
</style>
</head>
<body>
<!-- Office. chat-mount.js sets src to the open URL -->
<iframe id="editor" title="Thinkfree Office document"></iframe>
<!-- mountChat renders the chat UI inside #chat (shadow DOM) and attaches the agent -->
<section id="side">
<div id="status">Preparing…</div>
<div id="chat"></div>
</section>
<script type="module" src="./chat-mount.js"></script>
</body>
</html>
chat-mount.js
import { mountChat } from "@thinkfree.dev/tfo-ai-sdk/chat";
const OPEN_URL = "YOUR_OFFICE_DOCUMENT_OPEN_URL";
const MODULE = "word"; // "word" | "cell" | "show"
const $status = document.getElementById("status");
const editorEl = document.getElementById("editor");
// 1. Open Office. hideContentBar=1 hides Office's built-in AI Agent panel
const editorUrl = new URL(OPEN_URL);
editorUrl.searchParams.set("hideContentBar", "1");
editorEl.src = editorUrl.toString();
// 2. One call: render the chat UI in #chat, create the agent, connect Office's document tools
const chat = mountChat({
el: document.getElementById("chat"),
office: { iframeEl: editorEl, module: MODULE }, // the origin is derived from iframe.src
aiProviderConfig: "office", // default: Office's admin AI Provider settings
ui: { locale: "en" },
agent: { preset: "core" },
onToolCall: (e) => {
if (e.phase === "result") console.log(e.success ? "✓" : "✕", e.name, e.error ?? "");
},
});
// 3. Document tools registered: the chat can now work on the document
chat.ready
.then((toolNames) => {
$status.textContent = `Connected · ${toolNames.length} document tools · ${chat.session.uiToolNames.length} chat UI tools`;
})
.catch((err) => { $status.textContent = `Connection failed: ${err.code ?? ""} ${err.message}`; });
// 4. Clean up: glue -> agent -> UI
window.addEventListener("pagehide", () => chat.destroy());
예상 결과: 왼쪽에 문서, 오른쪽에 Thinkfree 채팅이 뜨고 상태 줄에 문서 도구 개수와 채팅 UI 도구 8개가
표시됩니다. "Add the heading 'Quarterly summary' at the top"처럼 요청하면 진행 칩, 편집 계획 카드, 결과 알림이 뜨고
문서가 바뀝니다. /tools를 입력하면 모델을 호출하지 않고 등록된 도구 목록을 보여 줍니다.
옵션
| 옵션 | 뜻 |
|---|---|
el | 필수. 채팅을 둘 요소. UI는 섀도 DOM 안에 그려져 페이지 CSS의 영향을 받지 않고, 요소의 높이를 채웁니다 |
office | 처음 연결할 Thinkfree Office { iframeEl, module, frameworkOrigin? }. 생략하면 UI만 뜨고 나중에 attachDocument()로 연결합니다 |
aiProviderConfig | "office"(기본) 또는 relay·direct 설정 |
agent | 에이전트 옵션: preset(core, review, full, 기본 full), systemPrompt, sessionId, sdkTimeoutMs, readyTimeoutMs |
ui | UI 옵션: locale, messages, variant(기본 hostChat), fontBase, device, onClose, onPointerDown. 페이지에 맞추기 참고 |
session | 연결 옵션: 첨부 훅(attachments.intercept, resolveMime), 모델에 보이는 messages, 추가 콜백(onAbort, onClear, onSettingsChange) |
onToolCall | 도구 호출 리스너. agent.onToolCall()과 같습니다 |
| 핸들 멤버 | 뜻 |
|---|---|
ui, agent, session | 세 층: 채팅 UI 컴포넌트, 헤드리스 에이전트, 연결 |
ready | 처음 office로 연결한 문서의 도구 등록이 끝나면 도구 이름 목록으로 resolve합니다. office를 생략하면 바로 빈 목록으로 resolve합니다 |
attachDocument(options), detachDocument() | 문서 연결, 교체, 분리. UI에 표시되는 모듈도 함께 바뀝니다 |
destroy() | 연결 → 에이전트 → UI 순서로 모두 정리합니다. 멱등 |
문서 바꾸기, 도구 호출 이벤트, 정리
// Switch documents: tools are registered again and "office" settings are re-read
chat.detachDocument();
editorEl.src = ANOTHER_OPEN_URL;
await new Promise((r) => editorEl.addEventListener("load", r, { once: true }));
await chat.attachDocument({ iframeEl: editorEl, module: "show" });
// Observe tool calls (same event as the headless agent)
const off = chat.agent.onToolCall((e) => { /* e.phase, e.name, e.success, e.result, e.error */ });
// Put a request into the chat from your own page, for example an "Ask AI" button
chat.ui.triggerInput("Add the heading 'Quarterly summary' at the top");
// Clean up
chat.destroy();
- 대화 이력은 에이전트의 세션이 보관합니다. 채팅 헤더의 초기화 버튼이 새 대화를 시작하고, 코드로는
destroy()후 다시mountChat()을 호출합니다. chat.session.bridge는 UI 뒤의 채팅 UI 브리지이며notify(),setSettings(),triggerInput()등 브리지 API를 그대로 쓸 수 있습니다.
페이지에 맞추기
- 언어와 문구.
ui.locale은en,ko를 내장합니다. 문구를 바꾸거나 다른 언어를 더하려면ui.messages로 덮어씁니다. - 글꼴. 번들은 글꼴 파일을 포함하지 않고 페이지 글꼴을 상속합니다. Pretendard를 쓰려면
ui.fontBase에 woff2 파일이 있는 디렉터리 URL을 주십시오. 문서 head에@font-face가 한 번 추가됩니다. - 닫기 버튼. 기본
variant: "hostChat"에는 닫기 버튼이 없습니다. 페이지에서 패널을 접을 수 있으면variant: "embedded"와onClose훅을 함께 쓰십시오. - 태블릿.
ui.device: "tablet"이면 터치 간격이 넓어집니다. 자동으로 판정하지 않습니다. - 스타일 격리. 페이지 CSS는 섀도 DOM 안에 닿지 않습니다.
ui.noShadow: true로 격리를 끌 수 있지만 권장하지 않습니다.
규칙
- 모델은 프롬프트, 대화 이력, 도구 스키마, 그리고 도구가 읽은 문서 내용을 포함한 도구 결과를 받습니다. 브라우저 밖으로 나가도 되는 것을 정하십시오. 안전 가이드를 참고하십시오.
- 이미 적용된 편집은 되돌아가지 않습니다. 기본 편집 수락 모드에서는 큰 편집을 사용자가 편집 계획 카드에서 먼저 봅니다.
/chat은 약 1.7MB입니다. 첫 로드가 무거우면 사용자가 채팅을 열 때 동적import()로 불러오십시오.
문제 해결
| 증상 | 확인 |
|---|---|
| 채팅 영역이 비어 있음 | mountChat()이 예외를 던졌거나 el의 높이가 0입니다. 콘솔을 확인하고 요소에 높이를 주십시오. |
ready가 TIMEOUT으로 거부됨 | 열기 URL이 아니거나 Thinkfree Office가 iframe src와 다른 origin에서 뜹니다. 문서 URL을 참고하십시오. |
| 첫 전송에서 공급자 오류 | "office"인데 Thinkfree Office에 관리자 AI Provider 설정이 없습니다. 객체를 넘겼다면 헤드리스 에이전트 문제 해결을 참고하십시오. |
| 글꼴이 페이지와 다름 | 번들에 글꼴 파일이 없습니다. ui.fontBase를 주거나 페이지 글꼴을 그대로 쓰십시오. |
/headless도 import함 | 런타임이 두 번 로드됩니다. 별도 import를 지우고 chat.agent를 쓰십시오. |
| 모델이 도구 없이 말로만 답함 | 구체적으로 요청하고 agent: { preset: "core" }로 도구를 줄이십시오. |