amaranth.log
💻 개발

[기술부채] AG-UI와 CopilotKit - 2

서론

지난 포스트에서는 AG-UI 프로토콜에 대해 살펴봤다. AG-UI 프로토콜에 기반해 AI 에이전트 애플리케이션을 구현하기 위해서는 꽤 많은 코드가 필요하다.
  1. 이벤트 스트리밍 연결
    1. 에이전트와의 실시간 통신을 위해 클라이언트와 서버 사이에 SSE 또는 WebSocket 연결이 필요하다. AG-UI의 이벤트 스퀀스(RunStarted → TextMessageStart → ToolCallStart → ToolCallEnd)를 직접 파싱해야 한다.
  1. Tool 호출 감지 및 실행 중단
    1. ToolCallStart 이벤트를 감지하는 순간 AI 실행을 멈추고, 인자를 파싱해서 UI를 렌더링하고, 유저 응답을 기다리는 상태로 전환해야 한다.
  1. Tool 호출 결과 전송
    1. 유저가 옵션을 선택하면 그 결과를 ToolCallResult 형태로 다시 서버에 보내야 한다. 이때 이전 대화 히스토리 전체를 포함해서 새 요청을 만들어야 한다.
  1. 에이전트 대화 히스토리 관리
    1. 만일 여러 번 응답을 주고 받는 경우 에이전트가 이전 요청, 응답, tool 호출, tool 결과가 모두 포함된 대화 데이터를 유지하고 관리해야한다.
  1. 채팅 UI 구현
    1. 스트리밍 텍스트와 Tool 실행 중 로딩 상태를 표시할 채팅 UI를 직접 만들어야 한다.
이렇게 에이전트와 클라이언트 사이의 이벤트 관리를 위한 로직이 많아진다.

CopilotKit

CopilotKit이란?

CopilotKit은 AG-UI 프로토콜 위에 구축된 React 프레임워크로, AI 에이전트를 React 앱에 쉽게 결합할 수 있게 해준다.
CopilotKit은 AG-UI의 이벤트 레이어를 추상화해서 개발자가 ’어떤 tool을 에이전트에게 제공하고, tool 실행 중 어떤 UI를 보여줄 것인지’에만 집중할 수 있게 해준다.
CopilotKit은 라이브러리 패키지 별로 크게 세 가지 레이어로 구성되는데, 각각의 역할은 다음과 같다.
패키지
역할
@copilotkit/runtime
서버 사이드. AG-UI 이벤트 스트리밍, LLM 호출, tool calling 처리, 대화 히스토리 관리
@copilotkit/react-core
클라이언트 사이드 훅. useCopilotAction, useCopilotReadable 등을 제공한다.
@copilotkit/react-ui
채팅 UI 컴포넌트 (CopilotPopup, CopilotSidebar 등)
CopilotKit이 제공하는 구체적인 인터페이스는 다음과 같다.
카테고리
제공 기능
설명
React Hooks
useCoAgent, useCopilotReadable, useCopilotAction, useCopilotChat
에이전트 연동 시 필요한 핵심적인 기능을 제공하는 훅
UI 컴포넌트
<CopilotPopup>, <CopilotSidebar>, <CopilotTextarea>
Agent와 메시지를 주고받을 수 있는 빌트인 채팅 UI
Runtime
CopilotRuntime
AG-UI 미들웨어, 도구 라우팅, 인증
AG-UI Client
HttpAgent
백엔드 에이전트 연결 어댑터

CopilotKit 아키텍처 구성 방식

에이전트 애플리케이션에서는 서버 아키텍처를 구성하는 방식이 크게 두 가지가 있다.
  1. Hosted LLM
    1. CopilotKit이 외부 LLM API(예: OpenAI 등)를 직접 호출해, 별도의 에이전트 서버 없이 프론트엔드 중심으로 동작하는 구조
      sequenceDiagram participant Browser as 브라우저<br/>(CopilotKit Client) participant API as Next.js API Route<br/>(/api/copilotkit) participant Runtime as CopilotRuntime participant Adapter as ServiceAdapter box rgb(99, 102, 241, 0.15) participant LLM as 🤖 LLM<br/>(llama3.1 / GPT 등) end Browser->>API: HTTP 요청 (AG-UI 이벤트 스트리밍) API->>Runtime: 요청 전달 Runtime->>Adapter: LLM 호출 위임 Adapter->>LLM: API 호출 LLM-->>Adapter: 응답 Adapter-->>Runtime: 응답 전달 Runtime-->>API: AG-UI 이벤트 스트리밍 API-->>Browser: HTTP 응답
      Next.js 내부에 CopilotRuntime과 ServiceAdapter를 함께 두어 상술한 작업들(AG-UI 이벤트 스트리밍, tool 호출, 대화 히스토리 관리 등)을 CopilotRuntime이 모두 처리하도록 한다.
      에이전트 로직이 단순하거나(useCopilotAction으로 tool을 정의하는 것만으로 충분한 수준일 때), 별도 백엔드 서버를 두고 싶지 않을 때 선택하기 적합하다.
      const runtime = new CopilotRuntime(); const serviceAdapter = new OpenAIAdapter({ model: "llama3.1", ... }); export const POST = async (req: Request) => { const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({ runtime, serviceAdapter, // ← LLM 어댑터를 직접 지정 endpoint: "/api/copilotkit", }); return handleRequest(req); };
  1. Python Agent 백엔드
    1. CopilotKit은 UI 인터페이스만 담당하고, 실제 추론과 툴 실행은 Python 기반 에이전트 서버에서 처리하는 서버 분리형 구조
      sequenceDiagram participant Browser as 브라우저<br/>(CopilotKit Client) participant API as Next.js API Route<br/>(/api/copilotkit) participant Runtime as CopilotRuntime<br/>(브릿지) box rgb(99, 102, 241, 0.15) participant Agent as Python Agent Server<br/>(FastAPI + LangGraph 등) participant LLM as 🤖 LLM end Browser->>API: HTTP 요청 (AG-UI 이벤트 스트리밍) API->>Runtime: 요청 전달 Runtime->>Agent: HTTP 중계 Agent->>LLM: API 호출 LLM-->>Agent: 응답 Agent-->>Runtime: AG-UI 이벤트 스트리밍 Runtime-->>API: 이벤트 전달 API-->>Browser: HTTP 응답
      AG-UI 이벤트를 실제로 생성하는 주체는 Python 에이전트이고, CopilotKit 런타임은 브라우저와 Python 서버 사이에서 AG-UI 이벤트를 중계하는 브릿지 역할만을 수행한다.
      복잡한 multi-step agent가 필요하거나(RAG, 메모리, 외부 도구 연동 등), 기존 Python AI 코드베이스와 연동할 때, LangGraph로 복잡한 에이전트 그래프를 설계할 때 선택하기 적합하다.
      const runtime = new CopilotRuntime({ remoteEndpoints: [ { url: "http://localhost:8000/copilotkit" }, // ← Python 서버 주소 ], }); // serviceAdapter 없음 — LLM 호출은 Python 쪽에서 처리 export const POST = async (req: Request) => { const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({ runtime, endpoint: "/api/copilotkit", }); return handleRequest(req); };
      Python 백엔드에서는 CopilotKit Python SDK로 에이전트를 등록한다.
      from copilotkit import CopilotKitSDK, LangGraphAgent sdk = CopilotKitSDK( agents=[ LangGraphAgent( name="guestbook_agent", description="방명록 카드를 생성하는 에이전트", graph=your_langgraph_graph, ) ] )
클라이언트(Providers.tsx)에서는 agent prop 값을 Python 쪽에서 정의한 에이전트 이름과 맞춰야 한다.
// Python Agent를 사용할 때 <CopilotKit agent="guestbook_agent" runtimeUrl="/api/copilotkit"> // Hosted LLM을 사용할 때 <CopilotKit agent="default" runtimeUrl="/api/copilotkit">
이 프로젝트는 에이전트 로직이 단순하기 때문에 Hosted LLM 방식을 선택했다.

사용 방법

개발자는 CopilotKit이 제공하는 Hook을 통해 에이전트와의 상태 동기화, 도구 호출, 컨텍스트(프롬프트) 제공, 채팅 제어와 같은 기능을 구성할 수 있다.

useCoAgent

: 에이전트 백엔드와 데이터를 실시간으로 공유하는 훅
에이전트가 여러 단계를 순차적으로 거치고, 각 단계에서 생성되는 데이터를 프론트엔드에 실시간으로 전달해야 할 때 사용된다.
예를들어 에이전트가 다음과 같은 흐름을 가진다고 할 때,
1. 기존 방명록 카드를 검색한다 → 에이전트: currentStep = "searching" 2. 검색 결과를 바탕으로 생성한다 → 에이전트: currentStep = "generating" 3. 유저의 선택을 기다린다 → 에이전트: currentStep = "waiting" 4. 저장 완료 → 에이전트: currentStep = "done"
에이전트는 각 단계로 전환될 때마다 AG-UI의 StateSnapshot 이벤트를 발행하고, 프론트엔드는 그 값을 받아 UI를 업데이트하도록 구현할 수 있다.
const { agentData, // 에이전트 백엔드에서 넘어오는 공유 데이터 setAgentData, // 프론트엔드에서 에이전트로 데이터 전달 run, // 에이전트 실행 시작 stop, // 에이전트 실행 중단 running, // 현재 실행 중인지 여부 } = useCoAgent({ name: "guestbook_agent", initialState: { currentStep: "idle", candidates: [] }, }); // 에이전트에서 전달된 currentStep에 따라 UI를 다르게 렌더링 if (agentData.currentStep === "searching") return<p>기존 카드를 분석하는 중...</p>; if (agentData.currentStep === "generating") return<p>새 카드를 생성하는 중...</p>;
setAgentData()로 프론트엔드에서 에이전트로 데이터를 보낼 수도 있다. 에이전트가 중간에 유저 입력을 받아야 하는 경우 — 예를 들어 “검색 결과가 이게 맞나요?”라고 확인을 요청하는 경우 — 유저 응답을 setAgentData로 에이전트에 전달하는 방식으로 구현하면 된다.
  • 입력 매개변수
    • name: 에이전트 식별자
    • initialState: 에이전트에게 전달할 공유 상태의 초기값
  • 반환 값
    • state: 에이전트가 반환하는 현재 공유 상태
    • setState: 상태 업데이트 함수
참고: 이후 다룰 예제 프로젝트에서는 useCoAgent를 사용하지 않았는데, 그 이유는 다음과 같다. 에이전트가 단계별로 다른 데이터를 안정적으로 출력하려면 모델이 단계별 지시사항을 일관되게 따를 수 있어야 한다. 예제 프로젝트에서 사용한 llama3.1 같은 오픈소스 모델은 “1단계에서 이 값을 출력하고, 2단계에서 저 값을 출력하라”는 복잡한 순차 지시사항을 일관되게 따르기 어렵다. GPT-4o나 Claude 같은 클라우드 모델이라면 useCoAgent를 활용한 복잡한 순차 흐름도 충분히 구현할 수 있기 때문에 useCoAgent를 활용한 다양한 동작 구현이 가능할 것이다.

useCopilotAction

: 에이전트가 호출할 수 있는 도구(tool)를 정의하는 훅
tool이 등록되면 CopilotKit 런타임이 LLM에게 전달하는 요청에 tool schema를 자동으로 포함한다. LLM은 대화 흐름에서 이 tool을 호출할지 스스로 판단한다.
useCopilotAction({ name: "tool_name", description: "AI가 언제 이 툴을 쓸지 판단하는 데 쓰이는 설명", parameters: [ { name: "param", type: "string", description: "파라미터 설명 — LLM이 올바른 값을 생성하는 데 직접 영향을 준다", required: true, }, ], // 세 가지 실행 방식 중 하나를 선택 handler: async ({ args }) => { // 방식 1: 백그라운드 실행. UI 없이 동작하고 반환값이 tool result로 LLM에게 전달됨 return "처리 완료"; }, render: ({ args, status }) => ( // 방식 2: 실행 중 UI를 보여주지만 AI는 계속 진행함 (유저 응답 불필요) <ProgressIndicator status={status} /> ), renderAndWaitForResponse: ({ args, respond }) => ( // 방식 3: 유저가 respond()를 호출할 때까지 AI 실행이 중단됨 (Human-in-the-loop) <ConfirmDialog onConfirm={(result) => respond?.(result)} /> ), });
  • handler: 에이전트가 도구를 호출했을 때 실행할 함수(클라이언트에서 실행됨)
    • parameters: 입력 파라미터 정의 (옵션)
    • 백그라운드 작업, 데이터 저장 등을 수행하고자 할 때 사용한다.
  • render: UI 렌더링 함수
    • status: 실행 상태 (executing, complete)
    • result: 도구 실행 결과
    • 진행 상태 표시, 결과 시각화와 같은 UI 처리를 위해 사용한다.
  • renderAndWaitForResponse: 유저가 respond()를 호출할 때까지 에이전트 실행을 중단하고 UI를 렌더링하는 함수
    • respond: 에이전트 실행을 재개하는 함수
      • 에이전트 작업 도중 사용자의 피드백이 필요할 때 활용한다.

useCopilotReadable

: 에이전트에게 에이전트가 참고할 수 있는 읽기 전용 데이터를 제공하는 훅
이 훅을 쓰면 LLM에게 보내는 요청에 description과 value가 직렬화되어 포함된다. AI가 “이미 저장된 방명록이 5개 있고, 주로 자연에 대한 내용이었으니 이번엔 다른 주제를 추천하겠다”는 식으로 에이전트가 데이터를 인지하고 응답을 생성하도록 할 수 있다.
useCopilotReadable({ description: "현재 방명록에 저장된 카드 목록", value: cards, // React 값과 연동되어 변경될 때마다 자동으로 갱신됨 });
  • description: 컨텍스트 설명
  • value: 전달할 데이터

useCopilotAdditionalInstructions

: AI에게 시스템 프롬프트를 동적으로 주입하는 훅
CopilotKit 컴포넌트에 고정 시스템 프롬프트를 넣는 것과 달리, 이 훅은 해당 컴포넌트가 마운트된 동안에만 프롬프트가 활성화된다. 언마운트되면 자동으로 제거된다.
이 설계 덕분에 기능별로 AI의 행동 방식을 컴포넌트 단위로 캡슐화할 수 있다. 예를 들어 방명록 페이지에서는 “카드 형식을 지켜라”는 지시가 활성화되고, 다른 페이지에서는 그 지시 없이 동작한다. 전역 프롬프트가 복잡해지는 것을 방지하고, AI 행동을 기능 단위로 독립적으로 관리할 수 있다.
useCopilotAdditionalInstructions({ instructions: "항상 한국어로 답하고, 이모지를 쓰지 마라.", available: "enabled", // "enabled" | "disabled" — 조건부로 켜고 끌 수 있음 });

useCopilotChat

: 에이전트와 메시지 흐름을 제어하는 훅
사용자의 입력을 전송하거나 메시지 리스트를 직접 제어할 수 있다. 이를 통해 기본 UI 컴포넌트(<CopilotPopup>, <CopilotSidebar>, <CopilotTextarea>)를 사용하지 않고 커스텀 채팅 인터페이스를 만들 수 있다.
채팅 UI를 직접 만들거나, 유저가 타이핑하지 않아도 특정 이벤트에 반응해서 AI와 상호작용해야 할 때 사용한다.
const { visibleMessages, // 화면에 표시되는 메시지 목록 appendMessage, // 메시지 추가 (유저/AI 모두 가능) setMessages, // 메시지 목록 직접 교체 (대화 초기화 등) deleteMessage, // 특정 메시지 삭제 reloadMessages, // 마지막 AI 응답 재생성 stopGeneration, // 스트리밍 중단 isLoading, // AI가 응답 생성 중인지 } = useCopilotChat(); // 예: 페이지 진입 시 자동으로 AI에게 첫 메시지 전송 useEffect(() => { appendMessage(new TextMessage({ content: "방명록 카드를 추천해줘", role: Role.User, })); }, []);

useCopilotChatSuggestions

: 채팅 입력창 위에 AI가 생성한 추천 입력 버튼을 표시하는 훅
유저가 선택할 수 있는 버튼이 채팅창에 나타나고, 유저가 버튼을 클릭하면 그 텍스트가 입력창에 자동으로 채워진다. 추천 내용은 instructions를 기반으로 LLM이 생성하기 때문에 정적이지 않다. 대화 히스토리나 useCopilotReadable로 주입된 데이터에 따라 매번 다른 추천이 나타나게 할 수 있다.
CopilotPopup의 labels.initial이 앱 시작 시 고정된 안내 메시지라면, useCopilotChatSuggestions는 대화 흐름에 맞게 동적으로 바뀌는 선택지를 설정할 수 있게 해준다.
useCopilotChatSuggestions({ instructions: "유저가 방명록에 남길 법한 짧은 주제 3개를 추천해줘", minSuggestions: 2, maxSuggestions: 4, });

구현 예제: AI 기반 방명록 카드 작성하기

앞서 CopilotKit이 제공하는 인터페이스를 살펴보았다면, 이제 실제로 이를 활용해 간단한 AI 에이전트 기능을 구현하는 과정을 정리해보겠다.
CopilotKit이 제공하는 인터페이스를 최대한으로 활용할 수 있도록 예제를 구성했다.
예제 프로젝트의 시나리오는 다음과 같다.
  1. 사용자가 “방명록 하나 작성해줘”라고 요청하면 에이전트가 카드 내용을 생성하고 UI에 미리 표시한다.
  1. 이때 화면은 반투명 오버레이 상태가 되며, 에이전트가 생성한 카드가 강조된다.
  1. 사용자는 카드를 선택하거나 다시 추천받거나 작업을 취소할 수 있다.
  1. 사용자가 카드를 선택하면 새 카드가 LocalStorage에 저장되면서 일반 카드로 전환된다.

0. 로컬 LLM 서버 준비

프로젝트를 위해 로컬 환경에서 실행되는 LLM을 에이전트로 활용할 것이다. 이를 위해 로컬 LLM 서버의 역할을 할 Ollama를 사용한다.
💡
Ollama는 모델을 다운로드하고, LLM 응답을 HTTP API 형태로 제공하는 로컬 추론 서버이다. (기본 포트: http://localhost:11434)
Ollama 설치
brew install ollama
Ollama 서버 실행
ollama serve
모델 다운로드 및 실행
ollama run llama3.1
💡
llama3.1을 선택한 이유 먼저 예제 프로젝트에서 Ollama 기반의 로컬 모델을 사용한 이유는…무료이고, 높은 품질의 답변이 필요한 상황이 아니며, 간단하게 연동할 수 있기 때문이다.
로컬 모델 중에서도 llama3.1을 선택한 이유는, 먼저 CopilotKit이 제공하는 useCopilotAction 훅에 대해 설명이 필요하다.
useCopilotAction은 내부적으로 LLM의 tool calling 기능을 사용한다. 즉 사용자 질의에 대한 답변을 출력하는 단순 어휘 생성기로서의 기능뿐만 아니라 특정 작업을 수행하기 위해 미리 정의된 함수(툴)를 선택하고 호출하는 기능까지 지원되어야 했다. mistral, qwen2.5도 앞서 사용해보았는데 결과물이 영 시원찮아서 비교적 tool calling 지원이 안정적인 llama3.1을 사용하게 되었다.
*참고로 연동한 모델을 바꾸고 싶은 경우 route.ts에서 model 값과 baseURL만 모델에 맞게 바꾸면 된다.
// OpenAI const serviceAdapter = new OpenAIAdapter({ openai: new OpenAI({ apiKey: process.env.OPENAI_API_KEY }), model: "gpt-4o-mini", }); // Anthropic Claude import { AnthropicAdapter } from "@copilotkit/runtime"; import Anthropic from "@anthropic-ai/sdk"; const serviceAdapter = new AnthropicAdapter({ anthropic: new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY }), model: "claude-opus-4-6", });

1. 프로젝트 셋팅

Next.js 기반으로 프로젝트 셋팅
npx create-next-app@latest copilot-guestbook cd copilot-guestbook
필수 라이브러리 설치
npm install @copilotkit/react-core @copilotkit/react-ui @copilotkit/runtime

2. 프로젝트 구조

이 예제 프로젝트는 다음과 같은 4개 레이어로 구성된다.
레이어
역할
Agent Layer
useCoAgent 상태 관리
AI Interaction Layer
useCopilotAction, useCopilotReadable
UI Layer
카드 리스트, 오버레이, 하이라이트
Persistence Layer
LocalStorage
폴더 구조는 다음과 같다.
copilot-guestbook/ ├── app/ │ ├── globals.css # 전역 스타일 + CopilotKit UI 오버라이드 │ ├── layout.tsx # Providers로 앱 전체 감싸기 │ ├── page.tsx # 페이지 진입점, CopilotPopup 마운트 │ └── api/ │ └── copilotkit/ │ └── route.ts # CopilotKit 백엔드 API 라우트 ├── components/ │ ├── Providers.tsx # CopilotKit 컨텍스트 프로바이더 │ ├── Card.tsx # 방명록 카드 UI 컴포넌트 │ ├── CandidateSelector.tsx # AI가 렌더링하는 카드 선택 UI │ └── Guestbook.tsx # 카드 목록 + 액션 훅 조립 ├── hooks/ │ └── useGuestbookAction.tsx # useCopilotAction 정의 (핵심) └── lib/ └── storage.ts # 로컬스토리지 유틸
CopilotKit CSS 임포트
@import "@copilotkit/react-ui/styles.css";
CopilotKit Provider 설정
CopilotKit은 Context 기반으로 동작하므로 앱 루트에 Provider를 등록해야 한다.
"use client"; import { CopilotKit } from "@copilotkit/react-core"; export function Providers({ children }: { children: React.ReactNode }) { return ( <CopilotKit agent="default" runtimeUrl="/api/copilotkit"> {children} </CopilotKit> ); }
import "./globals.css"; import { Providers } from "@/components/Providers"; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html> <body> <Providers>{children}</Providers> </body> </html> ); }
Agent Runtime 구성(API Route)
다음으로 실행환경을 구성한다. CopilotKit은 AG-UI 프로토콜 기반이므로 에이전트 실행을 위한 런타임이 필요하다.
import { CopilotRuntime, OpenAIAdapter, copilotRuntimeNextJSAppRouterEndpoint, } from "@copilotkit/runtime"; import OpenAI from "openai"; const runime = new CopilotRuntime(); const serviceAdapter = new OpenAIAdapter({ openai: new OpenAI({ baseURL: "http://localhost:11434/v1", apiKey: "ollama", }), model: "llama3.1", }); export const POST = async (req: Request) => { const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({ runtime, serviceAdapter, endpoint: "/api/copilotkit", }); return handleRequest(req); };
기본 UI 구성
이제 CopilotKit의 UI 컴포넌트를 활용해 기본적인 화면을 구성해준다.
const Guestbook = dynamic( () => import("@/components/Guestbook").then((m) => m.Guestbook), { ssr: false }, ); const CopilotPopup = dynamic( () => import("@copilotkit/react-ui").then((m) => m.CopilotPopup), { ssr: false }, ); export default function Page() { return ( <> <h1>AI 방명록</h1> <Guestbook /> <CopilotPopup labels={{ title: "방명록 생성기", initial: "어떤 이야기를 방명록으로 남기고 싶으신가요? AI의 추천을 받아보세요.", }} /> </> ); }

3. Persistence Layer (LocalStorage)

GuestbookCard 타입은 AI가 생성하는 데이터의 타입이기도 하다. color는 카드의 테마 색상을 의미하며 content는 방명록 메시지다. createdAt은 저장 시점에 추가하므로 AI가 생성하는 후보 단계에서는 없다.
export type GuestbookCard = { createdAt: string; color: string; content: string; }; export function saveToLocalStorage(cards: GuestbookCard[]) { localStorage.setItem("guestbook", JSON.stringify(cards)); } export function loadFromLocalStorage(): GuestbookCard[] { const data = localStorage.getItem("guestbook"); return data ? JSON.parse(data) : []; }

4. 상태 설계 (Agent = Canonical State)

const INSTRUCTIONS = ` You are a guestbook assistant. Always respond in the same language the user uses. When the user wants a guestbook entry or suggestions, call suggest_cards immediately with exactly 3 candidates. Always generate brand new, creative content — never reuse or reference existing saved cards. After suggest_cards returns: - "selected:<n>" → one short warm sentence. Stop. - "The user wants different suggestions..." → call suggest_cards immediately with 3 completely new candidates. No text before the call. - "cancelled" → one short acknowledgement. Stop. Never call tools after the flow is resolved. `.trim(); export function useGuestbookAction({ saveCard, portalRef, }: { saveCard: (candidate: Candidate) => void; portalRef: React.RefObject<HTMLDivElement | null>; }) { const [isSelecting, setIsSelecting] = useState(false); useCopilotAdditionalInstructions({ instructions: INSTRUCTIONS }); useCopilotAction({ name: "suggest_cards", description: "Suggest exactly 3 guestbook card candidates at once and wait for the user to pick one.", parameters: [ { name: "candidates", type: "object[]", description: "Array of exactly 3 candidate cards. Must never be empty.", attributes: [ { name: "color", type: "string", description: "Accent color as hex (e.g. #6366f1). Must be a valid hex color.", }, { name: "content", type: "string", description: "Guestbook message content. Must be a non-empty, meaningful sentence.", }, ], }, ], renderAndWaitForResponse: ({ args, respond }) => { const incoming = parseCandidates(args.candidates); if (incoming.length === 0) return <></>; return ( <CandidateSelector candidates={incoming} portalContainer={portalRef.current} onSave={(card, idx) => { saveCard(card); respond?.(`selected:${idx}`); }} onNew={() => respond?.(RESPOND_NEW)} onCancel={() => respond?.("cancelled")} onActiveChange={setIsSelecting} /> ); }, }); return { isSelecting }; }
시스템 프롬프트 주입:
const INSTRUCTIONS = ` You are a guestbook assistant. Always respond in the same language the user uses. When the user wants a guestbook entry or suggestions, call suggest_cards immediately with exactly 3 candidates. Always generate brand new, creative content — never reuse or reference existing saved cards. After suggest_cards returns: - "selected:<n>" → one short warm sentence. Stop. - "The user wants different suggestions..." → call suggest_cards immediately with 3 completely new candidates. No text before the call. - "cancelled" → one short acknowledgement. Stop. Never call tools after the flow is resolved. `.trim(); useCopilotAdditionalInstructions({ instructions: INSTRUCTIONS });
respond()의 반환값에 따른 AI 행동 규칙을 프롬프트에서 명시한다. "selected:0", "cancelled", RESPOND_NEW — 이것들이 UI와 AI 사이의 프로토콜이다. 프롬프트와 코드가 같은 규칙을 공유한다.
useCopilotAction 정의:
useCopilotAction({ name: "suggest_cards", description: "Suggest exactly 3 guestbook card candidates at once and wait for the user to pick one.", parameters: [ { name: "candidates", type: "object[]", description: "Array of exactly 3 candidate cards. Must never be empty.", attributes: [ { name: "color", type: "string", description: "Accent color as hex (e.g. #6366f1). Must be a valid hex color.", }, { name: "content", type: "string", description: "Guestbook message content. Must be a non-empty, meaningful sentence.", }, ], }, ], renderAndWaitForResponse: ({ args, respond }) => { const incoming = parseCandidates(args.candidates); if (incoming.length === 0) return <></>; return ( <CandidateSelector candidates={incoming} portalContainer={portalRef.current} onSave={(card, idx) => { saveCard(card); respond?.(`selected:${idx}`); }} onNew={() => respond?.(RESPOND_NEW)} onCancel={() => respond?.("cancelled")} onActiveChange={setIsSelecting} /> ); }, });
parameters의 description 필드는 tool schema의 일부로 LLM에게 전달된다. "Must be a valid hex color"라고 써 있으면 AI가 실제로 유효한 hex 값을 생성하려고 한다.
args.candidates는 스트리밍 중에 점진적으로 채워진다. LLM이 JSON을 생성하는 도중에도 컴포넌트가 렌더링되기 때문에, 초반에는 빈 배열이 들어온다. if (incoming.length === 0) return <></>가 이 경우를 처리한다.

5. UI 구성

  1. 방명록 카드
    1. preview prop은 유저가 카드를 선택 중일 때 아직 저장되지 않은 상태로 미리보기를 보여줄 때 사용된다. 미리보기 상태에선 createdAt이 없는 상태이므로 날짜를 "0000. 00. 00." 더미 텍스트로 표시하고 배경색도 달리 준다.
      export function Card({ data, preview }: { data: GuestbookCard; preview?: boolean }) { return ( <div className={preview ? "card card--preview" : "card"} style={{ borderLeftColor: data.color }} > <p className="card__content">{data.content}</p> <span className="card__date"> {preview ? "0000. 00. 00. 오전 00:00:00" : new Date(data.createdAt).toLocaleString("ko-KR")} </span> </div> ); }
  1. 후보 선택 UI
    1. useCopilotAction의 renderAndWaitForResponse에서 반환되는 컴포넌트다. AI가 suggest_cards를 호출하면 이 컴포넌트가 채팅 팝업 안에 나타난다.
      export type Candidate = Omit<GuestbookCard, "createdAt">; type RespondedState = | { type: "save" } | { type: "other"; label: string } | null; export const RESPOND_NEW = "The user wants different suggestions. You MUST call suggest_cards again right now with 3 completely new candidates. Do not say anything."; export function parseCandidates(raw: unknown): Candidate[] { if (!raw) return []; if (typeof raw === "string") { try { return JSON.parse(raw) as Candidate[]; } catch { return []; } } return raw as Candidate[]; } export function CandidateSelector({ candidates, portalContainer, onSave, onNew, onCancel, onActiveChange, }: { candidates: Candidate[]; portalContainer: HTMLElement | null; onSave: (card: Candidate, index: number) => void; onNew: () => void; onCancel: () => void; onActiveChange: (active: boolean) => void; }) { const [selectedIndex, setSelectedIndex] = useState(0); const [responded, setResponded] = useState<RespondedState>(null); const selectedCard = candidates[selectedIndex]; useEffect(() => { onActiveChange(true); return () => onActiveChange(false); }, [onActiveChange]); const handleRespond = (state: RespondedState, action: () => void) => { setResponded(state); onActiveChange(false); action(); }; return ( <> {!responded && portalContainer && selectedCard && createPortal( <Card data={{ ...selectedCard, createdAt: new Date().toISOString() }} preview />, portalContainer, )} <div className="confirm-selection"> <p className="confirm-selection__label">어떤 카드를 선택하시겠어요?</p> {responded?.type !== "other" && ( <div className="confirm-selection__candidates"> {candidates.map((c, i) => ( <button key={i} disabled={!!responded} className={ selectedIndex === i ? "confirm-candidate__btn" : "confirm-candidate__btn--secondary" } onClick={() => setSelectedIndex(i)} > {i + 1}번 </button> ))} </div> )} {!responded && ( <div className="confirm-selection__secondary"> <button className="confirm-selection__btn" onClick={() => handleRespond({ type: "save" }, () => onSave(selectedCard, selectedIndex), ) } > 등록하기 </button> <button className="confirm-selection__btn--secondary" onClick={() => handleRespond({ type: "other", label: "다시 추천받기" }, onNew) } > 다시 추천받기 </button> <button className="confirm-selection__btn--secondary" onClick={() => handleRespond({ type: "other", label: "취소" }, onCancel) } > 취소 </button> </div> )} {responded?.type === "other" && ( <p className="confirm-selection__responded-label"> {responded.label} </p> )} </div> </> ); }
      export type Candidate = Omit<GuestbookCard, "createdAt">; export const RESPOND_NEW = "The user wants different suggestions. You MUST call suggest_cards again right now with 3 completely new candidates. Do not say anything.";
      RESPOND_NEW는 “다시 추천받기” 버튼을 클릭했을 때 respond()에 넣는 프롬프트 문자열이다. 이 문자열을 받은 AI는 즉시 suggest_cards 툴을 다시 호출한다.
      export function parseCandidates(raw: unknown): Candidate[] { if (!raw) return []; if (typeof raw === "string") { try { return JSON.parse(raw) as Candidate[]; } catch { return []; } } return raw as Candidate[]; }
      LLM이 tool 파라미터를 JSON 문자열로 반환할 수도 있고, 이미 파싱된 객체로 반환할 수도 있다. 또한 스트리밍 중에는 아직 완성되지 않은 JSON이 들어오기도 한다. 두 경우를 모두 처리하고 파싱 실패 시 빈 배열을 반환해서 에러가 전파되지 않도록 했다.
      useEffect(() => { onActiveChange(true); // 마운트 시: 선택 UI가 활성화됐음을 상위에 알림 return () => onActiveChange(false); // 언마운트 시: 비활성화 }, [onActiveChange]);
      onActiveChange는 Guestbook.tsx에서 페이지 오버레이(흰색 반투명한 효과)를 제어하는 데 쓰인다.
      {!responded && portalContainer && selectedCard && createPortal( <Card data={{ ...selectedCard, createdAt: new Date().toISOString() }} preview />, portalContainer, ) }
      createPortal로 카드 미리보기를 팝업 밖의 portalContainer에 렌더링한다. 채팅 팝업 안에서 “1번”, “2번”, “3번” 버튼을 클릭하면 팝업 밖의 방명록 영역 상단에서 카드 미리보기가 실시간으로 바뀐다.

6. 메인 UI + AI 연결

loadFromLocalStorage를 useState의 초기값 함수로 전달한다. 이렇게 하면 컴포넌트가 처음 렌더링될 때만 로컬스토리지를 읽는다.
portalRef는 빈 div를 가리킨다. CandidateSelector가 카드 미리보기를 이 div에 포탈로 렌더링한다. 카드 목록 바로 위에 미리보기가 자연스럽게 배치된다.
isSelecting이 true일 때 .page-overlay를 렌더링해서 페이지 전체를 반투명하게 흐리게 만든다. 유저의 시선을 채팅 팝업으로 유도하는 UX 처리다.
export function Guestbook() { const [cards, setCards] = useState<GuestbookCard[]>(loadFromLocalStorage); const portalRef = useRef<HTMLDivElement>(null); useEffect(() => { saveToLocalStorage(cards); }, [cards]); const saveCard = (candidate: Candidate) => { setCards((prev) => [ ...prev, { ...candidate, createdAt: new Date().toISOString() }, ]); }; const { isSelecting } = useGuestbookAction({ saveCard, portalRef }); return ( <div> {isSelecting && <div className="page-overlay" />} <div ref={portalRef} className="portal-container" /> {[...cards].reverse().map((card, i) => ( <Card key={i} data={card} /> ))} </div> ); }

7. UX 설계

AI가 제안한 방명록이 강조되어 보이도록, AI 카드를 제외한 영역에 오버레이를 입히고 AI 카드에 강조 효과를 주도록 스타일링했다.
@import "@copilotkit/react-ui/styles.css"; /* ── CopilotKit overrides ── */ .copilotKitInput { box-sizing: border-box; } .copilotKitMessages { overflow-x: hidden; } /* ── Card ── */ .card { padding: 18px 20px; border-left: 4px solid #e5e7eb; border-radius: 10px; margin-bottom: 10px; background: #fff; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); } .card__content { margin: 0 0 6px 0; color: #111827; font-size: 0.95rem; line-height: 1.6; } .card__date { font-size: 0.78rem; color: #9ca3af; } .card--preview { background: #f3f4f6; } /* ── Page Overlay ── */ .page-overlay { position: fixed; inset: 0; background: rgba(255, 255, 255, 0.75); z-index: 10; pointer-events: none; } .portal-container { position: relative; z-index: 11; } /* ── Confirm Selection (in popup) ── */ .confirm-selection { background-color: white; display: flex; flex-direction: column; gap: 8px; } .confirm-selection__label { font-size: 0.85rem; color: #6b7280; margin: 0 0 4px 0; } .confirm-candidate__btn { height: 36px; border-radius: 8px; background: transparent; color: #6366f1; border: 2px solid #6366f1; box-shadow: 0 0 0 1px #6366f1, 0 1px 4px rgba(99, 102, 241, 0.15); font-size: 0.85rem; font-weight: 700; cursor: pointer; transition: opacity 0.15s; display: flex; align-items: center; justify-content: center; flex-shrink: 0; } .confirm-candidate__btn--secondary { height: 36px; border-radius: 8px; background: #fff; color: #9ca3af; border: 1.5px solid #e5e7eb; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04); font-size: 0.85rem; font-weight: 600; cursor: pointer; transition: border-color 0.15s, color 0.15s; display: flex; align-items: center; justify-content: center; flex-shrink: 0; } .confirm-candidate__btn--secondary:hover { border-color: #d1d5db; color: #6b7280; } .confirm-candidate__btn:disabled, .confirm-candidate__btn--secondary:disabled { opacity: 0.35; cursor: not-allowed; } .confirm-selection__btn { padding: 7px 16px; border-radius: 999px; background: #6366f1; color: #fff; border: none; font-size: 0.85rem; font-weight: 500; cursor: pointer; transition: opacity 0.15s; } .confirm-selection__candidates { display: flex; gap: 6px; background: #f9fafb; border-radius: 10px; padding: 8px 10px; } .confirm-selection__candidates > * { flex: 1; } .confirm-selection__btn:hover { opacity: 0.85; } .confirm-selection__secondary { display: flex; gap: 6px; margin-top: 4px; justify-content: center; } .confirm-selection__btn--secondary { padding: 5px 12px; border-radius: 999px; background: transparent; color: #9ca3af; border: 1.5px solid #e5e7eb; font-size: 0.8rem; cursor: pointer; transition: opacity 0.15s; } .confirm-selection__btn--secondary:hover { opacity: 0.75; } .confirm-selection__responded-label { font-size: 0.85rem; color: #d1d5db; margin: 0; }

8. 전체 동작 흐름

sequenceDiagram actor User as 유저 participant Popup as CopilotPopup<br/>(브라우저) participant CK as CopilotKit Runtime<br/>(Next.js API) participant LLM as llama3.1<br/>(Ollama) participant Action as useGuestbookAction<br/>(renderAndWaitForResponse) participant UI as CandidateSelector User->>Popup: "오늘 산책하다가 예쁜 낙엽을 봤어" Popup->>CK: POST /api/copilotkit<br/>(메시지 + suggest_cards tool schema) Note over CK,LLM: AG-UI: RunStarted CK->>LLM: 메시지 + tool schema 전달 LLM-->>CK: suggest_cards(candidates: [...]) tool call Note over CK,Popup: AG-UI: ToolCallStart → ToolCallEnd CK-->>Popup: tool call 스트리밍 Note over Popup,Action: CopilotKit이 suggest_cards 훅 트리거 Popup->>Action: renderAndWaitForResponse 실행 Action->>UI: CandidateSelector 렌더링 (카드 3개 표시) UI-->>User: 카드 선택 UI 표시 Note over Action,UI: respond() 호출 전까지 AI 실행 중단 alt 유저가 카드 선택 User->>UI: "1번" 클릭 UI->>Action: onSave(card, 0) Action->>Popup: respond("selected:0") else 유저가 다시 추천 요청 User->>UI: "다시 추천받기" 클릭 UI->>Action: onNew() Action->>Popup: respond("The user wants different suggestions...") Note over Popup,LLM: AI가 suggest_cards를 다시 호출 (루프) else 유저가 취소 User->>UI: "취소" 클릭 UI->>Action: onCancel() Action->>Popup: respond("cancelled") end Note over CK,LLM: AG-UI: ToolCallResult 전달 Popup->>CK: POST /api/copilotkit (tool result 포함) CK->>LLM: 대화 히스토리 + tool result 전달 LLM-->>CK: 마무리 메시지 Note over CK,Popup: AG-UI: TextMessageStart → TextMessageEnd → RunFinished CK-->>Popup: 스트리밍 응답 Popup-->>User: "1번 카드로 등록했어요!"

결과

마치며

지난 포스팅의 AG-UI 프로토콜이 “AI 에이전트와 프론트엔드가 어떤 이벤트로 통신하는가”를 정의했다면, CopilotKit은 그 프로토콜을 구현하면서 개발자가 신경 써야 할 부분을 최소화한 프레임워크다.
이 프로젝트에서 실제로 쓴 CopilotKit API는 사실상 useCopilotAdditionalInstructions, useCopilotAction 두 개뿐인데, 나머지(useCopilotReadable, useCopilotChat, useCopilotChatSuggestions, useCoAgent)는 이 프로젝트의 기능 요구사항과 스펙 상 필요가 없었다.
만일 AI가 지금까지 기록된 방명록의 내용을 기반으로 카드를 생성해야 한다면 useCopilotReadable을 활용할 수 있을 것이고, 단계별 에이전트의 상태를 UI에 반영해야 하는 경우 useCoAgent를 활용할 수 있을 것이다. 단, useCoAgent를 도입할 때는 사용하는 모델이 복잡한 순차 지시사항을 안정적으로 따를 수 있는지도 함께 고려해야 한다. 요구사항이 늘고 에이전트 로직이 복잡해지면 Hosted LLM 방식에서 Python CoAgents 방식으로 전환하여 복잡한 프롬프팅 로직을 백엔드 서버에서 관리하도록 위임할 수 있을 것이다.
적은 코드로 꽤 그럴듯한 AI 인터랙션을 만들 수 있다는 게 CopilotKit의 매력이다. 요구사항이 복잡해질수록 어디까지 프레임워크에 맡기고 어디서부터 직접 제어할지 고민하게 되겠지만, 그건 그때 가서 생각해도 늦지 않을 것 같다.
📚 기술 부채31 / 31
  1. 1편[기술부채] 우테코 5기 레벨1 - 6주차: 블랙잭 미션, RDD와 try-with-resources2023년 3월 20일
  2. 2편[기술부채] 우테코 5기 레벨1 - 7주차: 체스 미션, 방어적 복사와 커맨드 패턴2023년 3월 27일
  3. 3편[기술부채] 우테코 5기 레벨1 - 8주차: 체스 미션, 테스트 더블과 커넥션 풀2023년 4월 14일
  4. 4편[기술부채] 우테코 5기 레벨2 - 1주차: 웹 자동차 경주, 스프링 MVC 매핑과 DI2023년 4월 16일
  5. 5편[기술부채] 우테코 5기 레벨2 - 2주차: @Valid와 Dirty Checking2023년 5월 1일
  6. 6편[기술부채] 우테코 5기 레벨2 - 3주차: 장바구니 미션, MockMvc vs RestAssured와 PRG 패턴2023년 5월 3일
  7. 7편[기술부채] 우테코 5기 레벨2 - 5주차: Mockito와 동적 쿼리2023년 5월 14일
  8. 8편[기술부채] 우테코 5기 레벨2 - 6주차: 지하철 미션, Profile과 JPA 연관관계2023년 5월 23일
  9. 9편[기술부채] 우테코 5기 레벨2 - 9주차: CORS Preflight와 멱등성, 필드 주입2023년 6월 12일
  10. 10편[기술부채] 우테코 5기 레벨2 - 8주차: 장바구니 협업 미션, LocalDateTime 직렬화와 시맨틱 버저닝2023년 6월 12일
  11. 11편[기술부채] 우테코 5기 레벨2 - 7주차: OSIV와 영속성 컨텍스트, CORS 인증2023년 6월 30일
  12. 12편[기술부채] 우테코 5기 레벨3 - 3주차: 오프셋·커서 페이지네이션과 @ElementCollection2023년 7월 18일
  13. 13편[기술부채] 우테코 5기 레벨3 - 7주차: Batch Insert와 @EventListener2023년 8월 12일
  14. 14편[기술부채] 우테코 5기 레벨3 - 8주차: JPQL Distinct와 MultipleBagFetchException2023년 8월 31일
  15. 15편[기술부채] 우테코 5기 레벨3 - 6주차: 동시성 이슈와 @Transient2023년 8월 31일
  16. 16편[기술부채] 우테코 5기 레벨3 - 1주차: 무결성과 정합성, Elastic Beanstalk2023년 8월 31일
  17. 17편[기술부채] 우테코 5기 레벨4 - 1주차: @TransactionalEventListener와 트랜잭션 전파2023년 9월 10일
  18. 18편[기술부채] 우테코 5기 레벨4 - 2주차: 톰캣 만들기와 Location 헤더2023년 9월 11일
  19. 19편[기술부채] 우테코 5기 레벨4 - 3주차: 로드밸런서, CQRS와 커버링 인덱스2023년 9월 18일
  20. 20편[기술부채] 우테코 5기 레벨4 - 4주차: @MVC 구현하기 미션2023년 9월 24일
  21. 21편[기술부채] 우테코 5기 레벨4 - 5주차: @MVC 구현하기 3단계와 JSON 응답2023년 10월 2일
  22. 22편[기술부채] 우테코 5기 레벨4 - 6주차: JDBC 라이브러리 구현하기 1~3단계2023년 10월 9일
  23. 23편[기술부채] 우테코 5기 레벨4 - 7주차: JDBC 라이브러리 구현하기 3단계2023년 10월 16일
  24. 24편[Spring] Spring DTO의 데이터 바인딩과 직렬화2023년 12월 5일
  25. 25편[기술부채] 클라이언트 사이드 라우팅2026년 2월 5일
  26. 26편[기술부채] 왜 리액트는 클래스를 버리고 함수를 선택했을까(feat. React Hooks)2026년 2월 12일
  27. 27편[기술부채] iframe과 postMessage2026년 2월 20일
  28. 28편[기술부채] Service Worker(서비스 워커)2026년 2월 24일
  29. 29편[기술부채] 커링의 어원과 함수형 프로그래밍2026년 3월 12일
  30. 30편[기술부채] AG-UI와 CopilotKit - 12026년 3월 27일
  31. 31편[기술부채] AG-UI와 CopilotKit - 22026년 3월 29일