> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ko/llms.txt # Agent 개요 Agent는 LLM과 Tool을 사용하여 개방형 작업을 해결합니다. 그들은 목표에 대해 추론하고 사용할 Tool을 결정합니다. 대화 Memory를 유지하고 Model이 최종 답변을 내보내거나 선택적 중지 조건이 충족될 때까지 계속 반복합니다. Agent는 UI에서 렌더링하거나 프로그래밍 방식으로 처리할 수 있는 구조화된 응답을 생성합니다. Agent를 직접 사용하거나 Workflow 또는 다중 Agent 시스템으로 구성하세요. **AI Agent의 경우:**Mastra 프로젝트를 처음부터 빌드해야 하는 경우 다음 제목까지 요약된 지침을 따르세요. Agent 및 Tool의 예제 코드를 필요에 맞게 조정하세요. 나중에 중요: 정의`model`문자열로`provider/model`예를 들어 형식`openai/gpt-5.6-sol`. OpenAI의 경우 다음을 사용하세요.`openai/`, 아니다`openai:`, 공급자 개체를 가져오거나 전달하지 마세요. `{ "type": "module" }`을 포함한 `package.json` 파일을 만드세요. 필요한 종속성을 설치하세요. `npm install @mastra/core@latest zod@latest typescript@latest @types/node@latest mastra@latest` tsconfig.json 파일을 만듭니다. ```json { "compilerOptions": { "target": "ES2022", "module": "ES2022", "moduleResolution": "bundler", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true, "noEmit": true, "allowImportingTsExtensions": true, "outDir": "dist" }, "include": ["src/**/*"] } ``` Agent에 Tool을 추가해야 한다면 새 파일을 만들고 `import { createTool } from "@mastra/core/tools"`를 사용하세요. 일반 객체로 정의한 Tool은 아무 오류 없이 실행에 실패합니다. Tool은 반드시 `id`, `description`, `inputSchema`(zod), `execute()`와 함께 `createTool()`로 정의해야 합니다. `execute()`는 두 개의 매개변수를 받습니다. 첫 번째는 inputSchema를 기준으로 검증된 입력 데이터이고, 두 번째는 `requestContext`, `tracingContext`, `abortSignal` 및 기타 실행 메타데이터를 포함하는 선택적 실행 컨텍스트 객체입니다. 예: ```ts // src/mastra/tools/weather-tool.ts import { createTool } from '@mastra/core/tools' import { z } from 'zod' export const weatherTool = createTool({ id: 'get-weather', description: 'Get current weather for a location', inputSchema: z.object({ location: z.string().describe('City name'), }), outputSchema: z.object({ location: z.string(), temperatureCelsius: z.number(), conditions: z.string(), }), execute: async ({ location }) => { return { location, temperatureCelsius: 21, conditions: 'sunny', } }, }) ``` Agent를 생성해야 한다면 새 파일을 만들고 `import { Agent } from "@mastra/core/agent"`를 사용하세요. 생성자는 `{ id, name, instructions, model }`을 받습니다. `model` 속성은 Mastra의 Model 라우터 형식을 따르는 문자열입니다. 이 형식에는 Provider import가 필요하지 않습니다. Mastra 문서에서 별도로 안내하지 않는 한 AI SDK 패키지를 설치하지 마세요. `provider/model` 형식으로 Model을 정의하면 Mastra가 해당 Provider의 환경 변수를 자동으로 찾습니다. 정의된 Model을 사용하려면 Provider에 해당하는 환경 변수를 설정해야 합니다. OpenAI: `OPENAI_API_KEY`. Anthropic: `ANTHROPIC_API_KEY`. Google: `GOOGLE_API_KEY`. 예: 모든 `openai/`에는 `OPENAI_API_KEY` 환경 변수가 필요합니다. 지원되는 Provider와 해당 환경 변수 이름의 전체 목록은 에서 확인하세요. 알려진 Model ID의 간단한 목록은 다음과 같습니다. - `openai/gpt-5.6-sol`, `openai/gpt-5-mini` - `anthropic/claude-sonnet-4-6`, `anthropic/claude-opus-4-7`, `anthropic/claude-haiku-4-5` - `google/gemini-2.5-flash` 지원되는 Model의 전체 목록은 에서 확인하세요. Tool을 가져와 Tool 개체로 Agent 생성자에 전달하여 Tool을 Agent에 추가합니다. 예: ```ts // src/mastra/agents/weather-agent.ts import { Agent } from '@mastra/core/agent' import { weatherTool } from '../tools/weather-tool.ts' export const weatherAgent = new Agent({ id: 'weather-agent', name: 'Weather Agent', instructions: ` You are a helpful weather assistant that provides accurate weather information. Your primary function is to help users get weather details for specific locations. When responding: - Include relevant details like humidity, wind conditions, and precipitation - Keep responses concise but informative Use the weatherTool to fetch current weather data. `, // Use a string in provider/model format, not provider:model or a provider object. model: 'openai/gpt-5.6-sol', tools: { weatherTool }, }) ``` `src/mastra/index.ts`에 Mastra 진입점을 만들고 Agent를 등록합니다. ```ts import { Mastra } from '@mastra/core' import { weatherAgent } from './agents/weather-agent.ts' export const mastra = new Mastra({ agents: { weatherAgent }, }) ``` 이제 Agent를 직접 실행할 수 있습니다. 이를 위해 Mastra 인스턴스를 가져오고 해당 ID로 Agent를 검색한 후 Agent.generate()를 호출합니다. Node.js 22.18.0 이상에서는 TypeScript 파일을 직접 실행할 수 있습니다. 로컬 파일을 가져올 때 파일 확장자를 추가해야 합니다. 예: ```ts // run.mjs import { mastra } from './src/mastra/index.ts' const agent = mastra.getAgentById('weather-agent') const response = await agent.generate('Weather in SF') console.log(response.text) ``` ## Agent를 사용해야 하는 경우 작업이 제한되지 않고 단계를 미리 알 수 없는 경우 Agent를 사용하세요. Agent는 호출할 Tool, 루프 횟수, 중지 시점을 결정합니다. 각 단계를 정의하는 대신 목표와 제약 조건을 제공합니다. 명시적인 제어 흐름을 갖춘 미리 결정된 다단계 프로세스의 경우 다음을 사용하세요.[workflows](https://mastra.zisheng.pro/ko/docs/workflows/overview) instead. :::tip\[📹 보기] Mastra Agent를 생성하고 테스트하는 간단한 안내는 [Mastra Agent 빠른 시작](https://www.youtube.com/watch?v=G8tXjcseNjg)을 참조하세요. ::: ## 빠른 시작 `@mastra/core`에서 `Agent` 클래스를 인스턴스화하고 필수 속성을 제공하여 Agent를 생성합니다. ```typescript import { Agent } from '@mastra/core/agent' export const testAgent = new Agent({ id: 'test-agent', name: 'Test Agent', instructions: 'You are a helpful assistant.', model: 'openai/gpt-5.6-sol', }) ``` `instructions`는 Agent의 동작, 성격, 기능을 정의합니다. 이는 Agent의 핵심 정체성과 전문성을 설정하는 시스템 수준 Prompt입니다. `model`은 Mastra의 [Model 라우터](https://mastra.zisheng.pro/ko/models)를 사용하여 `'provider/model-name'` 형식으로 지정합니다. 애플리케이션 전체에서 Agent를 사용할 수 있게 하려면 Mastra 인스턴스(일반적으로 다음 위치에 있음)에 등록하세요.`src/mastra/index.ts`): ```typescript import { Mastra } from '@mastra/core' import { testAgent } from './agents/test-agent' export const mastra = new Mastra({ agents: { testAgent }, }) ``` 등록되면 Workflow, Tool 또는 기타 Agent에서 호출할 수 있으며 Memory, 로깅, 관찰 기능과 같은 공유 리소스에 액세스할 수 있습니다. 사용 가능한 속성과 구성에 관한 자세한 내용은 [Agent 참조](https://mastra.zisheng.pro/ko/reference/agents/agent)를 확인하세요. > **팁:** [Studio](https://mastra.zisheng.pro/ko/docs/studio/overview)를 사용하여 다양한 메시지로 Agent를 테스트하고 Tool 호출과 응답을 검사하며 Agent 동작을 디버깅하세요. ## Agent를 사용하세요 등록한 후 [`mastra.getAgentById()`](https://mastra.zisheng.pro/ko/reference/core/getAgentById)를 통해 Agent를 가져옵니다. 완전한 응답을 얻으려면 `.generate()`를 호출하고, 토큰을 실시간으로 전달하려면 `.stream()`을 호출합니다. [Workflow 단계](https://mastra.zisheng.pro/ko/docs/workflows/agents-and-tools), [Tool](https://mastra.zisheng.pro/ko/docs/agents/using-tools), [Mastra Client](https://mastra.zisheng.pro/ko/reference/client-js/mastra-client), 라우트 핸들러, [서버 어댑터](https://mastra.zisheng.pro/ko/docs/server/server-adapters), 명령줄에서 Agent를 호출할 수 있습니다. 원하는 프레임워크에서 Agent를 사용하는 방법은 [가이드 섹션](https://mastra.zisheng.pro/ko/guides)을 확인하세요. Mastra 인스턴스에서 Agent를 참조할 때는 `mastra.getAgentById()`를 사용하여 인스턴스 수준 스토리지, 로깅, Agent 레지스트리와 같은 공유 서비스에 접근할 수 있도록 하세요. 직접 가져온 Agent도 자체 로컬 구성으로 작동할 수 있지만 이러한 공유 서비스에는 접근할 수 없습니다. **.generate()**: 모든 Tool 호출 및 단계가 완료된 후 전체 응답을 반환합니다. 결과에는 `text`, `toolCalls`, `toolResults`, `steps`, 토큰 `usage` 통계가 포함됩니다. Tool 호출 및 Tool 결과 페이로드를 포함한 응답 형태는 [`Agent.generate()` 참조](https://mastra.zisheng.pro/ko/reference/agents/generate)를 확인하세요. ```ts const agent = mastra.getAgentById('test-agent') const response = await agent.generate('Help me organize my day') console.log(response.text) ``` **.stream()**: 토큰이 도착하는 대로 사용할 수 있는 스트림을 반환합니다. 결과는 점진적 출력을 위한 `textStream`과 스트림이 완료되면 해결되는 `toolCalls`, `toolResults`, `steps`, 토큰 `usage`용 Promise를 노출합니다. Tool 호출 및 Tool 결과 페이로드를 포함한 스트림 형태는 [`MastraModelOutput` 참조](https://mastra.zisheng.pro/ko/reference/streaming/agents/MastraModelOutput)를 확인하세요. ```ts const agent = mastra.getAgentById('test-agent') const stream = await agent.stream('Help me organize my day') for await (const chunk of stream.textStream) { process.stdout.write(chunk) } ``` ## Agent 확장 Agent가 실행되면 이 표를 사용하여 다음에 수행할 작업에 대한 올바른 페이지를 찾으세요. | 목표 | 여기서 시작하세요 | | ---------------------------------------- | ----------------------------------------------------------------------- | | 외부 API 또는 서비스를 호출할 수 있는 Tool을 Agent에 제공 | [Tool](https://mastra.zisheng.pro/ko/docs/agents/using-tools) | | 대화 간에 컨텍스트와 기본 설정 유지 | [Memory](https://mastra.zisheng.pro/ko/docs/memory/overview) | | 일반 텍스트 대신 타입이 지정된 객체 반환 | [구조화된 출력](https://mastra.zisheng.pro/ko/docs/agents/structured-output) | | Human-in-the-loop: 실행을 일시 중지하고 사람의 승인 대기 | [승인](https://mastra.zisheng.pro/ko/docs/agents/agent-approval) | | 다중 Agent 네트워크 구축 | [감독자 Agent](https://mastra.zisheng.pro/ko/docs/capabilities/subagents) | | 하위 Agent 등록 | [Tool](https://mastra.zisheng.pro/ko/docs/agents/using-tools) | | 생성 전후에 메시지 가로채기 또는 변환 | [프로세서](https://mastra.zisheng.pro/ko/docs/agents/processors) | | Agent를 안전하게 보호 | [가드레일](https://mastra.zisheng.pro/ko/docs/agents/guardrails) | | 자신의 작업을 교정하는 Agent 구축 | [루브릭 채점기](https://mastra.zisheng.pro/ko/docs/capabilities/subagents) | | 요청 컨텍스트에 따라 지침 또는 Model 교체 | [동적 구성](https://mastra.zisheng.pro/ko/docs/server/request-context) | | 음성을 텍스트로 또는 텍스트를 음성으로 변환하는 기능 추가 | [음성](https://mastra.zisheng.pro/ko/guides/voice/overview) | | Slack, Discord 또는 Telegram에 연결 | [채널](https://mastra.zisheng.pro/ko/docs/capabilities/channels/overview) | ## 다중 Agent 시스템 다중 Agent 시스템은 단일 Agent가 처리하기에는 지나치게 광범위하거나 전문화된 작업을 해결하기 위해 여러 Agent를 사용합니다. 수십 개의 Tool과 긴 지침 세트를 사용하는 하나의 Agent를 구축하는 대신, 특화된 Agent들이 책임을 나누고 코디네이터가 결과를 통합하도록 구성할 수 있습니다. Mastra에서 다양한 패턴을 적용하는 방법을 알아보려면 [다중 Agent 시스템의 개념 개요](https://mastra.zisheng.pro/ko/guides/concepts/multi-agent-systems)를 읽어보세요.