에이전트 지속성
원문: Koog Documentation — agent-persistence 이 글은 Koog 공식 문서의 agent-persistence 페이지를 한국어로 옮긴 번역본입니다. 문서 구조와 링크 의미를 유지하되, MkDocs 전용 UI 문법은 블로그에서 읽기 좋도록 정리했습니다.
에이전트 지속성
Agent Persistence는 Koog 프레임워크에서 AI 에이전트에 대한 체크포인트 기능을 제공하는 기능입니다. 실행 중 특정 지점에서 에이전트 상태를 저장하고 복원하여 다음과 같은 기능을 활성화할 수 있습니다.
- 특정 지점에서 에이전트 실행 재개
- 이전 상태로 롤백
- 세션 전반에 걸쳐 상담원 상태 유지
주요 개념
체크포인트
체크포인트는 다음을 포함하여 실행의 특정 지점에서 에이전트의 전체 상태를 캡처합니다.
- 메시지 기록(사용자, 시스템, 보조자 및 도구 간의 모든 상호 작용)
- 현재 실행 중인 노드
- 현재 노드의 입력 데이터
- 생성 타임스탬프
체크포인트는 고유 ID로 식별되며 특정 에이전트와 연결됩니다.
설치
에이전트 지속성 기능을 사용하려면 에이전트 구성에 이를 추가하세요.
코틀린
1val agent = AIAgent(2 promptExecutor = executor,3 llmModel = OllamaModels.Meta.LLAMA_3_2,4) {5 install(Persistence) {6 // Use in-memory storage for snapshots7 storage = InMemoryPersistenceStorageProvider()8 }9}자바
1AIAgent<String, String> agent = AIAgent.builder()2 .promptExecutor(executor)3 .llmModel(OllamaModels.Meta.LLAMA_3_2)4 .install(Persistence.Feature, cfg -> {5 // Use in-memory storage for snapshots6 cfg.setStorage(new InMemoryPersistenceStorageProvider());7 })8.build();구성 옵션
에이전트 지속성 기능에는 세 가지 주요 구성 옵션이 있습니다.
- 스토리지 제공업체: 체크포인트를 저장하고 검색하는 데 사용되는 제공업체입니다.
- 지속적 지속성: 각 노드가 실행된 후 체크포인트가 자동으로 생성됩니다.
- 롤백 전략: 체크포인트로 롤백할 때 복원할 상태를 결정합니다.
스토리지 제공업체
체크포인트를 저장하고 검색하는 데 사용할 스토리지 공급자를 설정합니다.
코틀린
1install(Persistence) {2 storage = InMemoryPersistenceStorageProvider()3}자바
1AIAgent<String, String> agent = AIAgent.builder()2 .promptExecutor(executor)3 .llmModel(OllamaModels.Meta.LLAMA_3_2)4 .install(Persistence.Feature, cfg -> {5 cfg.setStorage(new InMemoryPersistenceStorageProvider());6 })7 .build();프레임워크에는 다음과 같은 기본 제공 공급자가 포함되어 있습니다.
InMemoryPersistenceStorageProvider: 체크포인트를 메모리에 저장합니다(애플리케이션이 다시 시작되면 손실됨).FilePersistenceStorageProvider: 파일 시스템에 대한 체크포인트를 유지합니다.NoPersistenceStorageProvider: 체크포인트를 저장하지 않는 무작동 구현입니다. 이것이 기본 공급자입니다.
PersistenceStorageProvider 인터페이스를 구현하여 사용자 정의 스토리지 공급자를 구현할 수도 있습니다.
자세한 내용은 Custom storage providers을 참조하세요.
지속적인 지속성
지속적인 지속성은 각 노드가 실행된 후 체크포인트가 자동으로 생성됨을 의미합니다. 지속적인 지속성을 비활성화하려면 아래 코드를 사용하십시오.
코틀린
1install(Persistence) {2 enableAutomaticPersistence = false3}자바
1AIAgent<String, String> agent = AIAgent.builder()2 .promptExecutor(executor)3 .llmModel(OllamaModels.Meta.LLAMA_3_2)4 .install(Persistence.Feature, cfg -> {5 cfg.setEnableAutomaticPersistence(true);6 })7 .build();지속적인 지속성이 비활성화된 경우에도 수동으로 검사점을 생성할 수 있습니다.
기본 사용법
체크포인트 생성
에이전트 실행의 특정 지점에 체크포인트를 생성하는 방법을 알아보려면 아래 코드 샘플을 참조하세요.
코틀린
1suspend fun example(context: AIAgentContext) {2 // Create a checkpoint with the current state3 val checkpoint = context.persistence().createCheckpointAfterNode(4 agentContext = context,5 nodePath = context.executionInfo.path(),6 lastOutput = outputData,7 lastOutputType = outputType,8 checkpointId = context.runId,9 version = 0L10 )1112 // The checkpoint ID can be stored for later use13 val checkpointId = checkpoint?.checkpointId14}자바
1// PersistenceKt.persistence() is the Java-accessible form of the Kotlin extension function2Persistence persistence = PersistenceKt.persistence(context);34// Create a checkpoint with the current state5AgentCheckpointData checkpoint = persistence.createCheckpointAfterNode(6 context,7 context.getExecutionInfo().path(),8 outputData,9 TypeToken.of(String.class),10 0L,11 context.getRunId()12);1314// The checkpoint ID can be stored for later use15String checkpointId = checkpoint != null ? checkpoint.getCheckpointId() : null;체크포인트에서 복원
특정 체크포인트에서 에이전트 상태를 복원하려면 아래 코드 샘플을 따르세요.
코틀린
1suspend fun example(context: AIAgentContext, checkpointId: String) {2 // Roll back to a specific checkpoint3 context.persistence().rollbackToCheckpoint(checkpointId, context)45 // Or roll back to the latest checkpoint6 context.persistence().rollbackToLatestCheckpoint(context)7}자바
1Persistence persistence = PersistenceKt.persistence(context);23// Roll back to a specific checkpoint4persistence.rollbackToCheckpoint(checkpointId, context);56// Or roll back to the latest checkpoint7persistence.rollbackToLatestCheckpoint(context);도구로 인해 발생한 모든 부작용 롤백
일부 도구에서는 부작용이 발생하는 것이 매우 일반적입니다. 특히 백엔드에서 에이전트를 실행하는 경우 일부 도구는 일부 데이터베이스 트랜잭션을 수행할 가능성이 높습니다. 이로 인해 에이전트가 시간을 거슬러 여행하는 것이 훨씬 더 어려워집니다.
데이터베이스에 새 사용자를 생성하는 도구 createUser이 있다고 상상해 보십시오. 그리고 귀하의 에이전트는 초과 근무를 통해 여러 도구 호출을 채웠습니다.
1tool call: createUser "Alex"23->>>> checkpoint-1 <<<<-45tool call: createUser "Daniel"6tool call: createUser "Maria"이제 체크포인트로 롤백하고 싶습니다. 에이전트 상태(메시지 기록 및 전략 그래프 노드 포함)를 복원하는 것만으로는
체크포인트 이전에 세계의 정확한 상태를 파악하는 데 충분합니다. 또한 도구 호출로 인해 발생한 부작용도 복원해야 합니다. 우리의 예에서는
이는 데이터베이스에서 Maria 및 Daniel을 제거하는 것을 의미합니다.
Koog Persistence를 사용하면 RollbackToolRegistry에서 Persistence 기능 구성을 제공하여 이를 달성할 수 있습니다.
코틀린
1install(Persistence) {2 enableAutomaticPersistence = true3 rollbackToolRegistry = RollbackToolRegistry {4 // For every `createUser` tool call there will be a `removeUser` invocation in the reverse order 5 // when rolling back to the desired execution point.6 // Note: `removeUser` tool should take the same exact arguments as `createUser`. 7 // It's the developer's responsibility to make sure that `removeUser` invocation rolls back all side-effects of `createUser`:8 registerRollback(::createUser, ::removeUser)9 }10}자바
1AIAgent<String, String> agent = AIAgent.builder()2 .promptExecutor(executor)3 .llmModel(OllamaModels.Meta.LLAMA_3_2)4 .install(Persistence.Feature, cfg -> {5 cfg.setEnableAutomaticPersistence(true);6 cfg.setRollbackToolRegistry(7 RollbackToolRegistry.builder()8 // For every tool in UserToolSet there will be a corresponding rollback tool9 // in UserRollbackToolSet, invoked in reverse order when rolling back.10 // UserRollbackToolSet methods must be annotated with @Reverts to link11 // them to the corresponding tools in UserToolSet.12 .registerRollbacks(new UserToolSet(), new UserRollbackToolSet())13 .build()14 );15 })16 .build();확장 기능 사용
에이전트 지속성 기능은 체크포인트 작업을 위한 편리한 확장 기능을 제공합니다.
코틀린
1suspend fun example(context: AIAgentContext) {2 // Access the checkpoint feature3 val checkpointFeature = context.persistence()45 // Or perform an action with the checkpoint feature6 context.withPersistence { ctx ->7 // 'this' is the checkpoint feature8 createCheckpointAfterNode(9 agentContext = ctx,10 nodePath = ctx.executionInfo.path(),11 lastOutput = outputData,12 lastOutputType = outputType,13 checkpointId = ctx.runId,14 version = 0L15 )16 }17}자바
1// Access the persistence feature via PersistenceKt (the Kotlin extension function)2Persistence persistence = PersistenceKt.persistence(context);34// Use the persistence feature directly to create a checkpoint5persistence.createCheckpointAfterNode(6 context,7 context.getExecutionInfo().path(),8 outputData,9 TypeToken.of(String.class),10 0L,11 context.getRunId()12);고급 사용법
맞춤형 스토리지 제공업체
PersistenceStorageProvider 인터페이스를 구현하여 사용자 정의 스토리지 공급자를 구현할 수 있습니다.
코틀린
1class MyCustomStorageProvider<MyFilterType> : PersistenceStorageProvider<MyFilterType> {2 override suspend fun getCheckpoints(sessionId: String, filter: MyFilterType?): List<AgentCheckpointData> {3 TODO("Not yet implemented")4 }56 override suspend fun saveCheckpoint(sessionId: String, agentCheckpointData: AgentCheckpointData) {7 TODO("Not yet implemented")8 }910 override suspend fun getLatestCheckpoint(sessionId: String, filter: MyFilterType?): AgentCheckpointData? {11 TODO("Not yet implemented")12 }13}자바
1class MyCustomStorageProvider extends AsyncPersistenceStorageProvider<Object> {2 @Override3 public CompletableFuture<List<AgentCheckpointData>> getCheckpointsAsync(4 String agentId, Object filter) {5 throw new UnsupportedOperationException("Not yet implemented");6 }78 @Override9 public CompletableFuture<Boolean> saveCheckpointAsync(10 String agentId, AgentCheckpointData checkpointData) {11 throw new UnsupportedOperationException("Not yet implemented");12 }1314 @Override15 public CompletableFuture<AgentCheckpointData> getLatestCheckpointAsync(16 String agentId, Object filter) {17 throw new UnsupportedOperationException("Not yet implemented");18 }19}기능 구성에서 사용자 지정 공급자를 사용하려면 에이전트 지속성을 구성할 때 이를 스토리지로 설정하세요. 에이전트의 기능입니다.
코틀린
1install(Persistence) {2 storage = MyCustomStorageProvider<Any>()3}자바
1AIAgent<String, String> agent = AIAgent.builder()2 .promptExecutor(executor)3 .llmModel(OllamaModels.Meta.LLAMA_3_2)4 .install(Persistence.Feature, cfg -> {5 cfg.setStorage(new MyCustomStorageProvider());6 })7 .build();실행 지점 설정
고급 제어를 위해 에이전트의 실행 지점을 직접 설정할 수 있습니다.
코틀린
1suspend fun example(context: AIAgentContext) {2 // You can set the execution point before some node and provide an input for it:3 context.persistence().setExecutionPoint(4 agentContext = context,5 nodePath = context.executionInfo.path(),6 messageHistory = customMessageHistory,7 input = customInput8 )910 // Or after some node and provide an output from the node:11 context.persistence().setExecutionPointAfterNode(12 agentContext = context,13 nodePath = context.executionInfo.path(),14 messageHistory = customMessageHistory,15 output = customOutput16 )17}18자바
1Persistence persistence = PersistenceKt.persistence(context);23// Set the execution point before a node and provide an input for it:4persistence.setExecutionPoint(5 context,6 context.getExecutionInfo().path(),7 customMessageHistory,8 customInput9);1011// Or after a node and provide an output from the node:12persistence.setExecutionPointAfterNode(13 context,14 context.getExecutionInfo().path(),15 customMessageHistory,16 customOutput17);이를 통해 단순히 체크포인트에서 복원하는 것 이상으로 에이전트 상태를 더욱 세밀하게 제어할 수 있습니다.