CopilotKit 사용
부조종사 키트맞춤형 AI 부조종사를 애플리케이션에 신속하게 통합할 수 있는 React 구성 요소를 제공합니다. Mastra와 결합하면 양방향 상태 동기화 및 대화형 UI를 갖춘 AI 앱을 구축할 수 있습니다.
CopilotKit은 다음을 통해 Mastra와 대화합니다.AG-UI protocol. The @ag-ui/mastra패키지는 Mastra Agent를 AG-UI 엔드포인트로 노출하고 CopilotKit의 React 후크 및 구성 요소는 이를 사용합니다. 이를 통해 일반 채팅 외에도 다양한 경험을 누릴 수 있습니다.생성 UI, 인간 참여형(Human-In-The-Loop) 및 프런트엔드 Tool, 그리고 동일한 Agent를 다음에 배포Slack과 같은 메시징 채널.
방문CopilotKit documentation 에서 CopilotKit의 개념, 컴포넌트 및 고급 사용 패턴을 자세히 알아보세요.
Mastra가 Next.js API 경로에서 직접 실행되는 전체 스택 통합 접근 방식은 다음을 참조하세요.CopilotKit Quickstart guide.
마스트라(Mastra)를 방문해 보세요"UI Dojo" 에서 Mastra와 통합된 CopilotKit의 실제 사례를 확인하세요.
통합 가이드통합 가이드에 대한 직접 링크
Mastra를 독립형 서버로 실행하고 Next.js 프런트엔드(CopilotKit 포함)를 API 엔드포인트에 연결하세요.
디렉터리 구조를 설정합니다. 가능한 디렉터리 구조는 다음과 같습니다.
project-root├── mastra-server│ ├── src│ │ └── mastra│ └── package.json└── my-copilot-app└── package.jsonMastra 서버를 부트스트랩합니다.
- npm
- pnpm
- Yarn
- Bun
npx create-mastra@latestpnpm dlx create-mastra@latestyarn dlx create-mastra@latestbun x create-mastra@latest이 명령은 새로운 Mastra 프로젝트를 스캐폴드하는 대화형 마법사를 엽니다. 메시지에 따라 서버 프로젝트를 만듭니다.
새로 생성된 Mastra 서버 디렉터리로 이동합니다.
cd mastra-server # Replace with the actual directory name you provided이제 기본 Mastra 서버 프로젝트가 준비되었습니다.
노트다음에서 LLM 공급자에 대한 적절한 환경 변수를 설정했는지 확인하세요.
.envfile.다음을 사용하여 CopilotKit 프런트엔드에 대한 채팅 경로를 만듭니다.
registerCopilotKit()helper from@ag-ui/mastra. 이를 peer dependency와 함께 Mastra 프로젝트에 추가합니다:- npm
- pnpm
- Yarn
- Bun
npm install @ag-ui/mastra @mastra/client-js @mastra/core @ag-ui/core @ag-ui/client @copilotkit/runtimepnpm add @ag-ui/mastra @mastra/client-js @mastra/core @ag-ui/core @ag-ui/client @copilotkit/runtimeyarn add @ag-ui/mastra @mastra/client-js @mastra/core @ag-ui/core @ag-ui/client @copilotkit/runtimebun add @ag-ui/mastra @mastra/client-js @mastra/core @ag-ui/core @ag-ui/client @copilotkit/runtime당신의
src/mastra/index.tsfile, register the chat route:src/mastra/index.tsimport { Mastra } from '@mastra/core/mastra'import { registerCopilotKit } from '@ag-ui/mastra/copilotkit'// Rest of the imports...export const mastra = new Mastra({// Rest of the configuration...server: {cors: {origin: '*',allowMethods: ['*'],allowHeaders: ['*'],},apiRoutes: [registerCopilotKit({path: '/copilotkit',resourceId: 'weatherAgent',}),],},})이렇게 하면 Mastra 인스턴스의 Agent가 다음 위치에 노출됩니다.
/copilotkit를 CopilotKit 호환 형식으로 제공합니다. 프런트엔드는 다음agentprop을 사용하여 대화할 Agent를 선택합니다. CopilotKit 프런트엔드가 Mastra 서버에 접근할 수 있도록 CORS 구성을 추가하세요. 프로덕션 배포에서는 CORS origin을 프런트엔드 도메인으로 제한하세요.다음 명령을 사용하여 Mastra 서버를 실행하십시오.
- npm
- pnpm
- Yarn
- Bun
npm run devpnpm run devyarn devbun run dev기본적으로 Mastra 서버는 다음에서 실행됩니다.
http://localhost:4111. CopilotKit 프런트엔드를 설정하는 동안 이 서버를 계속 실행해 두세요.프로젝트 루트의 한 디렉터리로 이동합니다.
cd ..이름으로 새 Next.js 프로젝트를 만듭니다.
my-copilot-app:- npm
- pnpm
- Yarn
- Bun
npx create-next-app@latest my-copilot-apppnpm dlx create-next-app@latest my-copilot-appyarn dlx create-next-app@latest my-copilot-appbun x create-next-app@latest my-copilot-app새로 생성된 Next.js 프로젝트 디렉터리로 이동합니다.
cd my-copilot-app채팅 인터페이스를 표시하는 데 사용할 CopilotKit UI 패키지를 설치합니다.
- npm
- pnpm
- Yarn
- Bun
npm install @copilotkit/react-ui @copilotkit/react-corepnpm add @copilotkit/react-ui @copilotkit/react-coreyarn add @copilotkit/react-ui @copilotkit/react-corebun add @copilotkit/react-ui @copilotkit/react-coreNext.js 앱의 홈 경로를 엽니다(일반적으로
app/page.tsxorsrc/app/page.tsx)를 열고 기존 내용을 다음 코드로 교체하여 기본 CopilotKit 채팅 인터페이스를 설정합니다:app/page.tsximport { CopilotChat } from '@copilotkit/react-ui'import { CopilotKit } from '@copilotkit/react-core'import '@copilotkit/react-ui/styles.css'export default function Home() {return (<CopilotKit runtimeUrl="http://localhost:4111/copilotkit" agent="weatherAgent"><CopilotChatlabels={{title: 'Weather Agent',initial: 'Hi! 👋 Ask me about the weather, forecasts, and climate.',}}/></CopilotKit>)}그만큼
agentprop은 요청을 라우팅할 Mastra Agent의 이름을 지정합니다. 이 값은 Mastra 인스턴스의agentsmap.Mastra 서버와 CopilotKit 프런트엔드가 모두 실행되고 있는지 확인하세요. Next.js 개발 서버를 시작합니다:
- npm
- pnpm
- Yarn
- Bun
npm run devpnpm run devyarn devbun run dev브라우저에서 앱을 열고 Agent과 채팅하세요.
이제 CopilotKit 프런트엔드는 독립 실행형 Mastra Agent 서버와 통신합니다.
채팅 UI 옵션채팅 UI 옵션에 대한 직접 링크
CopilotChat인라인 전체 높이 채팅을 렌더링합니다. CopilotKit은 동일한 소품을 공유하는 두 개의 다른 드롭인 표면을 제공합니다.
CopilotSidebar: 앱 측면에 도킹된 접이식 패널입니다.CopilotPopup: 채팅 창을 여는 플로팅 버튼입니다.
표면을 변경하려면 구성요소를 교체하세요. 3개 모두 동일한 경로로 연결됩니다.CopilotKit provider:
import { CopilotSidebar } from '@copilotkit/react-ui'
import { CopilotKit } from '@copilotkit/react-core'
import '@copilotkit/react-ui/styles.css'
export default function Home() {
return (
<CopilotKit runtimeUrl="http://localhost:4111/copilotkit" agent="weatherAgent">
<CopilotSidebar
labels={{
title: 'Weather Agent',
initial: 'Hi! 👋 Ask me about the weather.',
}}
/>
{/* your app */}
</CopilotKit>
)
}
완전히 사용자 정의된 채팅 UI(자체 구성 요소 가져오기)를 보려면 다음을 참조하세요.CopilotKit's headless UI guide.
앱 제어 및 상호작용앱 제어 및 상호작용에 대한 직접 링크
Agent 출력을 UI로 렌더링하는 것 이상(참조generative UI)를 사용하면 CopilotKit이 Agent로 하여금 애플리케이션에서 작업을 수행하고 사용자를 기다리도록 일시 중지할 수 있습니다. 두 패턴 모두 동일한 Mastra 설정에서 실행됩니다.
프런트엔드 Tool프런트엔드 Tool에 대한 직접 링크
Agent에게 앱에서 작업할 수 있는 기능을 부여하세요. 프런트엔드에 Tool을 등록합니다.useFrontendTool; the handler runs in the browser when the agent calls it:
import { CopilotChat } from '@copilotkit/react-ui'
import { CopilotKit, useFrontendTool } from '@copilotkit/react-core'
function Chat() {
useFrontendTool({
name: 'colorChangeTool',
description: 'Changes the background color',
parameters: [
{ name: 'color', type: 'string', description: 'The color to change to', required: true },
],
handler: ({ color }) => {
document.body.style.setProperty('--background', color)
},
})
return <CopilotChat labels={{ title: 'Background Color Changer' }} />
}
export default function Page() {
return (
<CopilotKit runtimeUrl="http://localhost:4111/copilotkit" agent="bgColorAgent">
<Chat />
</CopilotKit>
)
}
매칭된 마스트라 Agent는 통화 지시를 받은 일반 Agent입니다.colorChangeTool with the requested color.
인간 참여형인간 참여형에 대한 직접 링크
Agent 실행 도중에 일시 중지하고 계속하기 전에 사용자가 승인, 편집 또는 거부할 때까지 기다립니다. 사용useHumanInTheLoop: its render function receives a respond callback을 제공하며, 이를 호출할 때까지 Agent의 실행은 일시 중단된 상태로 유지됩니다.
import { CopilotChat } from '@copilotkit/react-ui'
import { CopilotKit, useHumanInTheLoop } from '@copilotkit/react-core'
import { StepsFeedback } from '@/components/steps-feedback'
function Chat() {
useHumanInTheLoop({
name: 'generate_task_steps',
description: 'Generates a list of steps for the user to perform',
parameters: [
{
name: 'steps',
type: 'object[]',
attributes: [
{ name: 'description', type: 'string' },
{ name: 'status', type: 'string', enum: ['enabled', 'disabled', 'executing'] },
],
},
],
available: 'enabled',
// `respond` resumes the agent with the user's edited selection.
render: ({ args, respond, status }) => (
<StepsFeedback args={args} respond={respond} status={status} />
),
})
return <CopilotChat labels={{ title: 'Planning Agent' }} />
}
export default function Page() {
return (
<CopilotKit runtimeUrl="http://localhost:4111/copilotkit" agent="planningAgent">
<Chat />
</CopilotKit>
)
}
내부에StepsFeedback, let the user toggle steps and then call respond({ accepted: true, steps }) to resume the agent, or respond({ accepted: false }) 를 호출하면 거부합니다. Agent는 반환된 값을 읽고 그에 따라 계속 진행합니다. 전체 컴포넌트는 다음에서 확인하세요: UI Dojo.
위의 예에서는 클라이언트 Tool을 사용합니다. Agent 호출generate_task_steps and the frontend fulfills it through respond. Mastra는 서버에서도 일시 중지할 수 있으며, 사람이 승인하거나 입력을 제공할 때까지 Tool 호출이 실행되기 전에 중단합니다. 이 방식은 Mastra의 Agent approval guide for the backend side and CopilotKit's useHumanInTheLoop reference for the frontend.
구성 옵션구성 옵션에 대한 직접 링크
이것을 사용하세요registerCopilotKit() options for the common integration points:
| 옵션 | 그것을 사용하려면 |
|---|---|
path | Set the route path, such as /copilotkit. |
resourceId | Scope Mastra memory for conversations. |
cors | Configure per-route CORS in addition to server.cors. |
setContext | 인증 정보나 사용자별 리소스 ID 등 Agent가 실행되기 전에 요청 컨텍스트를 채웁니다. |
agents | Mastra 인스턴스에 등록된 Agent 대신 미리 구성된 AG-UI Agent를 제공합니다. |
tracingOptions | Mastra Trace 옵션을 각 Agent 실행에 전달합니다. |
기본적으로 엔드포인트는 Mastra 인스턴스에 등록된 모든 Agent를 노출하고 프런트엔드는 다음 중 하나를 선택합니다.agent prop을 통해 설정합니다. 그 밖의 CopilotKit 런타임 옵션은 기반 런타임으로 전달됩니다. 예시는 다음을 참조하세요: Open-ended generative UI for mcpApps.
전개전개에 대한 직접 링크
CopilotKit을 사용하여 Mastra 서버를 배포할 때 다음을 제외해야 합니다.@copilotkit/runtime 를 번들에서 제외합니다. 이 패키지에는 번들링과 호환되지 않는 dependency가 포함되어 있어 번들에 포함하면 500 오류가 발생합니다.
이 문제는 개발 중에는 발생하지 않습니다.mastra dev 는 번들링이 필요하지 않으므로 해당되지 않습니다. 하지만 다음을 실행하는 경우에는 누구나 mastra build for deployment will encounter this issue.
추가@copilotkit/runtime package to your bundler externals configuration:
export const mastra = new Mastra({
bundler: {
externals: ['@copilotkit/runtime'],
},
})