> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ko/llms.txt # 응답캐시 `ResponseCache`Agent 루프 내부의 요청/응답 경계에서 LLM 응답을 캐시하는 입력 프로세서입니다. 에 연결됩니다`processLLMRequest`캐시 조회 및 적중 시 단락을 위해. 그것은 사용한다`processLLMResponse`완성된 답변을 작성합니다. 캐시 키는 Mastra가 Model에 전송하려는, 해석이 완료된 `LanguageModelV2Prompt`에서 파생됩니다(즉, Memory가 로드되고 앞선 입력 프로세서가 Prompt를 변환한 _후_). 따라서 Memory 컨텍스트가 서로 다른 두 사용자는 서로 다른 캐시 키를 생성합니다. Agent형 Tool 루프의 각 단계는 독립적으로 캐시됩니다. 응답 캐싱을 위한 Agent 수준 옵션은 없습니다. `inputProcessors`에 `ResponseCache`를 명시적으로 등록하세요. 호출별 재정의는 [`ResponseCache.context()`](#static-helpers)와 [`ResponseCache.applyContext()`](#static-helpers)를 통해 `RequestContext`로 전달됩니다. ## 사용예 ```typescript import { Agent } from '@mastra/core/agent' import { InMemoryServerCache } from '@mastra/core/cache' import { ResponseCache } from '@mastra/core/processors' const cache = new InMemoryServerCache() const agent = new Agent({ id: 'search-agent', name: 'Search Agent', instructions: 'You answer questions concisely.', model: 'openai/gpt-5', inputProcessors: [new ResponseCache({ cache, ttl: 600 })], }) // First call hits the LLM and writes to the cache. await agent.generate('What is the capital of France?') // Second identical call replays the cached response. await agent.generate('What is the capital of France?') // Force a fresh call but still update the cache. await agent.generate('What is the capital of France?', { requestContext: ResponseCache.context({ bust: true }), }) ``` 개념 개요, 범위 지정 규칙, 권장 배포 패턴은 [응답 캐싱](https://mastra.zisheng.pro/ko/docs/agents/processors)을 참조하세요. ## 생성자 매개변수 **cache** (`MastraServerCache`): 캐시 백엔드입니다. 필수 항목입니다. 로컬 개발용 InMemoryServerCache, 프로덕션용 @mastra/redis의 RedisCache 또는 사용자 지정 백엔드를 위한 자체 하위 클래스 등 모든 MastraServerCache 구현을 전달할 수 있습니다. **ttl** (`number`): 이 프로세서가 작성한 항목의 TTL(초)입니다. OpenRouter의 참조 구현과 동일하게 기본값은 300초(5분)입니다. (Default: `300`) **scope** (`string | null`): 캐시 키에 추가되는 테넌트 범위입니다. null은 범위 지정을 사용하지 않습니다. 생략하면 프로세서는 요청 컨텍스트에서 해석된 리소스 ID(MASTRA\_RESOURCE\_ID\_KEY)를 사용하여 사용자별로 자동 격리합니다. **key** (`string | (inputs: ResponseCacheKeyInputs) => string | Promise`): 자동으로 파생된 캐시 키를 재정의합니다. 키를 고정하려면 문자열을 전달하고, { agentId, scope, model, prompt, stepNumber }를 받아 키를 반환하도록 하려면 함수를 전달하세요. 함수에서 오류가 발생하면 프로세서는 결정적 해시로 대체하므로 호출에서 계속 캐싱 효과를 얻을 수 있습니다. **bust** (`boolean`): 모든 호출에서 강제로 캐시 미스를 발생시킵니다. 읽기는 건너뛰지만 완료 시 쓰기는 계속 수행합니다. 명시적 새로 고침 경로에 유용합니다. (Default: `false`) **agentId** (`string`): 캐시 키 네임스페이스에 사용되는 논리적 ID입니다. 기본값은 'mastra-response-cache'입니다. 캐시 항목의 범위를 Agent별로 지정하려면 소유 Agent의 ID로 설정하세요. (Default: `'mastra-response-cache'`) ## 정적 도우미 `ResponseCache`는 `RequestContext`에 호출별 재정의를 설정하기 위한 두 개의 정적 도우미를 제공합니다. 도우미는 내부 컨텍스트 키를 비공개 구현 세부 정보로 유지합니다. 원시 키를 직접 읽거나 쓰는 대신 이 도우미를 사용하세요. ### `ResponseCache.context(options)` 호출별 응답 캐시 재정의가 미리 로드된 새 `RequestContext`를 생성합니다. ```typescript await agent.stream('hello', { requestContext: ResponseCache.context({ key: 'custom', bust: true }), }) ``` ### `ResponseCache.applyContext(requestContext, options)` 호출별 응답 캐시 재정의를 기존 `RequestContext`에 병합합니다. 체이닝할 수 있도록 같은 컨텍스트를 반환합니다. ```typescript const ctx = new RequestContext() ctx.set('caller-meta', { userId: 'u-123' }) ResponseCache.applyContext(ctx, { bust: true }) await agent.stream('hello', { requestContext: ctx }) ``` ## ResponseCacheContext옵션 전달된 모양`ResponseCache.context()` / `ResponseCache.applyContext()`. **key** (`string | (inputs: ResponseCacheKeyInputs) => string | Promise`): 이 요청에 대해서만 자동으로 파생된 캐시 키를 재정의합니다. **scope** (`string | null`): 이 요청에 대해서만 테넌트 범위를 재정의합니다. null은 범위 지정을 사용하지 않습니다. **bust** (`boolean`): 캐시 읽기는 건너뛰지만 완료 시 쓰기는 계속 수행합니다. `cache`, `ttl`, `agentId`는 의도적으로 호출별 재정의를 허용하지 않습니다. 요청마다 달라지면 안 되는 인스턴스 수준의 고려 사항이기 때문입니다. ## 응답캐시키 입력 `key` 함수(생성자 또는 호출별 함수)에 전달되는 인수입니다. 기본적으로 모든 필드가 결정적 해시에 반영됩니다. **agentId** (`string`): 캐시 키의 네임스페이스를 지정하는 데 사용되는 논리적 프로세서 ID입니다. **scope** (`string | null | undefined`): 이 요청에 대해 해석된 범위이며, 범위 지정이 비활성화되면 null입니다. **model** (`{ provider?: string; modelId?: string; specVersion?: string }`): Provider/Model ID입니다. Model이 다르면 응답도 달라집니다. **prompt** (`LanguageModelV2Prompt`): Memory가 로드되고 Prompt를 수정하는 모든 입력 프로세서가 실행된 후 Provider가 받게 되는 정확한 Prompt입니다. **stepNumber** (`number`): Agent형 루프 내에서 0부터 시작하는 단계 번호입니다. Tool 단계에서는 0보다 큽니다. ## 도우미 내보내기 - `buildResponseCacheKey(inputs)`: 기본적으로 사용되는 결정적 해시입니다. 나머지 표준 키 형식을 유지하면서 개별 필드를 재정의하려면 이를 다시 내보내세요. - `DEFAULT_RESPONSE_CACHE_TTL_SECONDS`: 기본 `ttl`(`300`)입니다. - `RESPONSE_CACHE_CONTEXT_KEY`: 정적 도우미가 쓰는 `RequestContext` 키입니다. 고급 사례(예: 파이프라인 중간에 재정의 지우기)를 위해 노출됩니다. 도우미를 우선 사용하세요. ## 관련된 - [응답 캐싱](https://mastra.zisheng.pro/ko/docs/agents/processors) - [프로세서](https://mastra.zisheng.pro/ko/docs/agents/processors) - [프로세서 인터페이스](https://mastra.zisheng.pro/ko/reference/processors/processor-interface)