> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ko/llms.txt
# CopilotKit 사용
[부조종사 키트](https://www.copilotkit.ai/)맞춤형 AI 부조종사를 애플리케이션에 신속하게 통합할 수 있는 React 구성 요소를 제공합니다. Mastra와 결합하면 양방향 상태 동기화 및 대화형 UI를 갖춘 AI 앱을 구축할 수 있습니다.
CopilotKit은 다음을 통해 Mastra와 대화합니다.[AG-UI protocol](https://docs.ag-ui.com/). The `@ag-ui/mastra`패키지는 Mastra Agent를 AG-UI 엔드포인트로 노출하고 CopilotKit의 React 후크 및 구성 요소는 이를 사용합니다. 이를 통해 일반 채팅 외에도 다양한 경험을 누릴 수 있습니다.[생성 UI, 인간 참여형(Human-In-The-Loop) 및 프런트엔드 Tool](https://mastra.zisheng.pro/ko/guides/build-your-ui/copilotkit/generative-ui), 그리고 동일한 Agent를 다음에 배포[Slack과 같은 메시징 채널](https://mastra.zisheng.pro/ko/guides/build-your-ui/copilotkit/channels).
방문[CopilotKit documentation](https://docs.copilotkit.ai/) 에서 CopilotKit의 개념, 컴포넌트 및 고급 사용 패턴을 자세히 알아보세요.
> **정보:** Mastra가 Next.js API 경로에서 직접 실행되는 전체 스택 통합 접근 방식은 다음을 참조하세요.[CopilotKit Quickstart](https://docs.copilotkit.ai/mastra/quickstart) guide.
마스트라(Mastra)를 방문해 보세요["UI Dojo"](https://ui-dojo.mastra.ai/) 에서 Mastra와 통합된 CopilotKit의 실제 사례를 확인하세요.
## 통합 가이드
Mastra를 독립형 서버로 실행하고 Next.js 프런트엔드(CopilotKit 포함)를 API 엔드포인트에 연결하세요.
1. 디렉터리 구조를 설정합니다. 가능한 디렉터리 구조는 다음과 같습니다.
```bash
project-root
├── mastra-server
│ ├── src
│ │ └── mastra
│ └── package.json
└── my-copilot-app
└── package.json
```
Mastra 서버를 부트스트랩합니다.
**npm**:
```bash
npx create-mastra@latest
```
**pnpm**:
```bash
pnpm dlx create-mastra@latest
```
**Yarn**:
```bash
yarn dlx create-mastra@latest
```
**Bun**:
```bash
bun x create-mastra@latest
```
이 명령은 새로운 Mastra 프로젝트를 스캐폴드하는 대화형 마법사를 엽니다. 메시지에 따라 서버 프로젝트를 만듭니다.
새로 생성된 Mastra 서버 디렉터리로 이동합니다.
```bash
cd mastra-server # Replace with the actual directory name you provided
```
이제 기본 Mastra 서버 프로젝트가 준비되었습니다.
> **노트:** 다음에서 LLM 공급자에 대한 적절한 환경 변수를 설정했는지 확인하세요.`.env` file.
2. 다음을 사용하여 CopilotKit 프런트엔드에 대한 채팅 경로를 만듭니다.`registerCopilotKit()` helper from `@ag-ui/mastra`. 이를 peer dependency와 함께 Mastra 프로젝트에 추가합니다:
**npm**:
```bash
npm install @ag-ui/mastra @mastra/client-js @mastra/core @ag-ui/core @ag-ui/client @copilotkit/runtime
```
**pnpm**:
```bash
pnpm add @ag-ui/mastra @mastra/client-js @mastra/core @ag-ui/core @ag-ui/client @copilotkit/runtime
```
**Yarn**:
```bash
yarn add @ag-ui/mastra @mastra/client-js @mastra/core @ag-ui/core @ag-ui/client @copilotkit/runtime
```
**Bun**:
```bash
bun add @ag-ui/mastra @mastra/client-js @mastra/core @ag-ui/core @ag-ui/client @copilotkit/runtime
```
당신의`src/mastra/index.ts` file, register the chat route:
```typescript
import { 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 호환 형식으로 제공합니다. 프런트엔드는 다음 `agent` prop을 사용하여 대화할 Agent를 선택합니다. CopilotKit 프런트엔드가 Mastra 서버에 접근할 수 있도록 CORS 구성을 추가하세요. 프로덕션 배포에서는 CORS origin을 프런트엔드 도메인으로 제한하세요.
3. 다음 명령을 사용하여 Mastra 서버를 실행하십시오.
**npm**:
```bash
npm run dev
```
**pnpm**:
```bash
pnpm run dev
```
**Yarn**:
```bash
yarn dev
```
**Bun**:
```bash
bun run dev
```
기본적으로 Mastra 서버는 다음에서 실행됩니다.`http://localhost:4111`. CopilotKit 프런트엔드를 설정하는 동안 이 서버를 계속 실행해 두세요.
4. 프로젝트 루트의 한 디렉터리로 이동합니다.
```bash
cd ..
```
이름으로 새 Next.js 프로젝트를 만듭니다.`my-copilot-app`:
**npm**:
```bash
npx create-next-app@latest my-copilot-app
```
**pnpm**:
```bash
pnpm dlx create-next-app@latest my-copilot-app
```
**Yarn**:
```bash
yarn dlx create-next-app@latest my-copilot-app
```
**Bun**:
```bash
bun x create-next-app@latest my-copilot-app
```
새로 생성된 Next.js 프로젝트 디렉터리로 이동합니다.
```bash
cd my-copilot-app
```
5. 채팅 인터페이스를 표시하는 데 사용할 CopilotKit UI 패키지를 설치합니다.
**npm**:
```bash
npm install @copilotkit/react-ui @copilotkit/react-core
```
**pnpm**:
```bash
pnpm add @copilotkit/react-ui @copilotkit/react-core
```
**Yarn**:
```bash
yarn add @copilotkit/react-ui @copilotkit/react-core
```
**Bun**:
```bash
bun add @copilotkit/react-ui @copilotkit/react-core
```
Next.js 앱의 홈 경로를 엽니다(일반적으로`app/page.tsx` or `src/app/page.tsx`)를 열고 기존 내용을 다음 코드로 교체하여 기본 CopilotKit 채팅 인터페이스를 설정합니다:
```typescript
import { CopilotChat } from '@copilotkit/react-ui'
import { CopilotKit } from '@copilotkit/react-core'
import '@copilotkit/react-ui/styles.css'
export default function Home() {
return (
)
}
```
그만큼`agent` prop은 요청을 라우팅할 Mastra Agent의 이름을 지정합니다. 이 값은 Mastra 인스턴스의 `agents` map.
6. Mastra 서버와 CopilotKit 프런트엔드가 모두 실행되고 있는지 확인하세요. Next.js 개발 서버를 시작합니다:
**npm**:
```bash
npm run dev
```
**pnpm**:
```bash
pnpm run dev
```
**Yarn**:
```bash
yarn dev
```
**Bun**:
```bash
bun run dev
```
브라우저에서 앱을 열고 Agent과 채팅하세요.
이제 CopilotKit 프런트엔드는 독립 실행형 Mastra Agent 서버와 통신합니다.
## 채팅 UI 옵션
`CopilotChat`인라인 전체 높이 채팅을 렌더링합니다. CopilotKit은 동일한 소품을 공유하는 두 개의 다른 드롭인 표면을 제공합니다.
- `CopilotSidebar`: 앱 측면에 도킹된 접이식 패널입니다.
- `CopilotPopup`: 채팅 창을 여는 플로팅 버튼입니다.
표면을 변경하려면 구성요소를 교체하세요. 3개 모두 동일한 경로로 연결됩니다.`CopilotKit` provider:
```typescript
import { CopilotSidebar } from '@copilotkit/react-ui'
import { CopilotKit } from '@copilotkit/react-core'
import '@copilotkit/react-ui/styles.css'
export default function Home() {
return (
{/* your app */}
)
}
```
완전히 사용자 정의된 채팅 UI(자체 구성 요소 가져오기)를 보려면 다음을 참조하세요.[CopilotKit's headless UI guide](https://docs.copilotkit.ai/).
## 앱 제어 및 상호작용
Agent 출력을 UI로 렌더링하는 것 이상(참조[generative UI](https://mastra.zisheng.pro/ko/guides/build-your-ui/copilotkit/generative-ui))를 사용하면 CopilotKit이 Agent로 하여금 애플리케이션에서 작업을 수행하고 사용자를 기다리도록 일시 중지할 수 있습니다. 두 패턴 모두 동일한 Mastra 설정에서 실행됩니다.
### 프런트엔드 Tool
Agent에게 앱에서 작업할 수 있는 기능을 부여하세요. 프런트엔드에 Tool을 등록합니다.`useFrontendTool`; the `handler` runs in the browser when the agent calls it:
```tsx
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
}
export default function Page() {
return (
)
}
```
매칭된 마스트라 Agent는 통화 지시를 받은 일반 Agent입니다.`colorChangeTool` with the requested color.
### 인간 참여형
Agent 실행 도중에 일시 중지하고 계속하기 전에 사용자가 승인, 편집 또는 거부할 때까지 기다립니다. 사용`useHumanInTheLoop`: its `render` function receives a `respond` callback을 제공하며, 이를 호출할 때까지 Agent의 실행은 일시 중단된 상태로 유지됩니다.
```tsx
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 }) => (
),
})
return
}
export default function Page() {
return (
)
}
```
내부에`StepsFeedback`, let the user toggle steps and then call `respond({ accepted: true, steps })` to resume the agent, or `respond({ accepted: false })` 를 호출하면 거부합니다. Agent는 반환된 값을 읽고 그에 따라 계속 진행합니다. 전체 컴포넌트는 다음에서 확인하세요: [UI Dojo](https://ui-dojo.mastra.ai/).
위의 예에서는 클라이언트 Tool을 사용합니다. Agent 호출`generate_task_steps` and the frontend fulfills it through `respond`. Mastra는 서버에서도 일시 중지할 수 있으며, 사람이 승인하거나 입력을 제공할 때까지 Tool 호출이 실행되기 전에 중단합니다. 이 방식은 Mastra의 [Agent approval](https://mastra.zisheng.pro/ko/docs/agents/agent-approval) guide for the backend side and CopilotKit's [`useHumanInTheLoop`](https://docs.copilotkit.ai/reference/hooks/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](https://mastra.zisheng.pro/ko/guides/build-your-ui/copilotkit/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:
```typescript
export const mastra = new Mastra({
bundler: {
externals: ['@copilotkit/runtime'],
},
})
```