트레이싱

·3분 읽기

원문: Koog Documentation — tracing 이 글은 Koog 공식 문서의 tracing 페이지를 한국어로 옮긴 번역본입니다. 문서 구조와 링크 의미를 유지하되, MkDocs 전용 UI 문법은 블로그에서 읽기 좋도록 정리했습니다.

트레이싱

이 페이지에는 AI 에이전트에 대한 포괄적인 추적 기능을 제공하는 추적 기능에 대한 세부정보가 포함되어 있습니다.

기능 개요

추적 기능은 에이전트 실행에 대한 자세한 정보를 캡처하는 강력한 모니터링 및 디버깅 도구입니다. 다음을 포함:

  • 전략 실행
  • LLM 통화
  • LLM 스트리밍(시작, 프레임, 완료, 오류)
  • 도구 호출
  • 에이전트 그래프 내 노드 실행

이 기능은 에이전트 파이프라인에서 주요 이벤트를 가로채서 구성 가능한 메시지로 전달하는 방식으로 작동합니다. 프로세서. 이러한 프로세서는 추적 정보를 로그 파일이나 기타 유형과 같은 다양한 대상으로 출력할 수 있습니다. 파일 시스템의 파일을 관리하여 개발자가 에이전트 동작에 대한 통찰력을 얻고 문제를 효과적으로 해결할 수 있도록 합니다.

이벤트 흐름

  1. 추적 기능은 에이전트 파이프라인에서 이벤트를 가로챕니다.
  2. 이벤트는 구성된 메시지 필터를 기반으로 필터링됩니다.
  3. 필터링된 이벤트는 등록된 메시지 프로세서로 전달됩니다.
  4. 메시지 프로세서는 이벤트의 형식을 지정하고 해당 대상으로 출력합니다.

구성 및 초기화

기본 설정

추적 기능을 사용하려면 다음을 수행해야 합니다.

  1. 하나 이상의 메시지 프로세서를 갖습니다(기존 프로세서를 사용하거나 직접 생성할 수 있음).
  2. 에이전트에 Tracing을 설치합니다.
  3. 메시지 필터를 구성합니다(선택 사항).
  4. 기능에 메시지 프로세서를 추가합니다.

코틀린

1// Defining a logger/file that will be used as a destination of trace messages 2val logger = KotlinLogging.logger { }3val outputPath = Path("/path/to/trace.log")45// Creating an agent6val agent = AIAgent(7    promptExecutor = simpleOllamaAIExecutor(),8    llmModel = OllamaModels.Meta.LLAMA_3_2,9) {10    install(Tracing) {11        // Configure message processors to handle trace events12        addMessageProcessor(TraceFeatureMessageLogWriter(logger))13        addMessageProcessor(TraceFeatureMessageFileWriter.create(outputPath))14    }15}

자바

1// Defining a logger/file that will be used as a destination of trace messages2var logger = LoggerFactory.getLogger("tracing");3var outputPath = Path.of("/path/to/trace.log");45// Creating an agent6var agent = AIAgent.builder()7    .promptExecutor(PromptExecutor.builder().ollama().build())8    .llmModel(OllamaModels.Meta.LLAMA_3_2)910    .install(Tracing.Feature, config -> {11        // Configure message processors to handle trace events12        config.addMessageProcessor(TraceFeatureMessageLogWriter.create(logger));13        config.addMessageProcessor(TraceFeatureMessageFileWriter.create(outputPath));14    })15    .build();

메시지 필터링

기존 이벤트를 모두 처리하거나 특정 기준에 따라 일부를 선택할 수 있습니다. 메시지 필터를 사용하면 처리되는 이벤트를 제어할 수 있습니다. 이는 특정 측면에 초점을 맞추는 데 유용합니다. 에이전트가 실행됩니다:

코틀린

12val fileWriter = TraceFeatureMessageFileWriter(3    outputPath,4    { path: Path -> SystemFileSystem.sink(path).buffered() }5)67addMessageProcessor(fileWriter)89// Filter for LLM-related events only10fileWriter.setMessageFilter { message ->11    message is LLMCallStartingEvent || message is LLMCallCompletedEvent12}1314// Filter for tool-related events only15fileWriter.setMessageFilter { message -> 16    message is ToolCallStartingEvent ||17        message is ToolCallCompletedEvent ||18        message is ToolValidationFailedEvent ||19        message is ToolCallFailedEvent20}2122// Filter for node execution events only23fileWriter.setMessageFilter { message -> 24    message is NodeExecutionStartingEvent || message is NodeExecutionCompletedEvent25}

자바

1var fileWriter = TraceFeatureMessageFileWriter.create(2    outputPath,3    path -> { try { return Files.newOutputStream(path); } catch (IOException e) { throw new UncheckedIOException(e); }}4);56config.addMessageProcessor(fileWriter);78// Filter for LLM-related events only9fileWriter.setMessageFilter(message ->10    message instanceof LLMCallStartingEvent || message instanceof LLMCallCompletedEvent11);1213// Filter for tool-related events only14fileWriter.setMessageFilter(message ->15    message instanceof ToolCallStartingEvent ||16        message instanceof ToolCallCompletedEvent ||17        message instanceof ToolValidationFailedEvent ||18        message instanceof ToolCallFailedEvent19);2021// Filter for node execution events only22fileWriter.setMessageFilter(message ->23    message instanceof NodeExecutionStartingEvent || message instanceof NodeExecutionCompletedEvent24);

큰 추적 볼륨

복잡한 전략이 있거나 장기간 실행되는 에이전트의 경우 추적 이벤트의 양이 상당할 수 있습니다. 이벤트 양을 관리하려면 다음 방법을 사용하는 것이 좋습니다.

  • 특정 메시지 필터를 사용하여 이벤트 수를 줄이세요.
  • 버퍼링 또는 샘플링을 사용하여 사용자 정의 메시지 프로세서를 구현합니다.
  • 로그 파일이 너무 커지는 것을 방지하려면 로그 파일에 파일 회전을 사용하십시오.

종속성 그래프

추적 기능에는 다음과 같은 종속성이 있습니다.

1Tracing2├── AIAgentPipeline (for intercepting events)3├── TraceFeatureConfig4│   └── FeatureConfig5├── Message Processors6│   ├── TraceFeatureMessageLogWriter7│   │   └── FeatureMessageLogWriter8│   ├── TraceFeatureMessageFileWriter9│   │   └── FeatureMessageFileWriter10│   └── TraceFeatureMessageRemoteWriter11│       └── FeatureMessageRemoteWriter12└── Event Types (from ai.koog.agents.core.feature.model)13    ├── AgentStartingEvent14    ├── AgentCompletedEvent15    ├── AgentExecutionFailedEvent16    ├── AgentClosingEvent17    ├── GraphStrategyStartingEvent18    ├── FunctionalStrategyStartingEvent19    ├── StrategyCompletedEvent20    ├── NodeExecutionStartingEvent21    ├── NodeExecutionCompletedEvent22    ├── NodeExecutionFailedEvent23    ├── SubgraphExecutionStartingEvent24    ├── SubgraphExecutionCompletedEvent25    ├── SubgraphExecutionFailedEvent26    ├── LLMCallStartingEvent27    ├── LLMCallCompletedEvent28    ├── LLMStreamingStartingEvent29    ├── LLMStreamingFrameReceivedEvent30    ├── LLMStreamingFailedEvent31    ├── LLMStreamingCompletedEvent32    ├── ToolCallStartingEvent33    ├── ToolValidationFailedEvent34    ├── ToolCallFailedEvent35    └── ToolCallCompletedEvent

예시 및 빠른 시작

로거에 대한 기본 추적

코틀린

1// Create a logger2val logger = KotlinLogging.logger { }34// Create an agent with tracing5val agent = AIAgent(6    promptExecutor = simpleOllamaAIExecutor(),7    llmModel = OllamaModels.Meta.LLAMA_3_2,8) {9    install(Tracing) {10        addMessageProcessor(TraceFeatureMessageLogWriter(logger))11    }12}1314// Run the agent15agent.run("Hello, agent!")

자바

1// Create a logger2var logger = LoggerFactory.getLogger("tracing");34// Create an agent with tracing5var agent = AIAgent.builder()6    .promptExecutor(PromptExecutor.builder().ollama().build())7    .llmModel(OllamaModels.Meta.LLAMA_3_2)89    .install(Tracing.Feature, config -> {10        config.addMessageProcessor(TraceFeatureMessageLogWriter.create(logger));11    })12    .build();1314// Run the agent15agent.run("Hello, agent!");

오류 처리 및 극단적인 경우

메시지 프로세서 없음

추적 기능에 메시지 프로세서가 추가되지 않으면 경고가 기록됩니다.

1Tracing Feature. No feature out stream providers are defined. Trace streaming has no target.

이 기능은 여전히 ​​이벤트를 가로채지만 어디에서도 처리되거나 출력되지 않습니다.

자원 관리

메시지 프로세서는 적절하게 해제되어야 하는 리소스(예: 파일 핸들)를 보유할 수 있습니다. use 확장 사용 적절한 정리를 보장하는 기능:

코틀린

1val writer = TraceFeatureMessageFileWriter(2    outputPath,3    { path: Path -> SystemFileSystem.sink(path).buffered() }4)56// Creating an agent7val agent = AIAgent(8    promptExecutor = simpleOllamaAIExecutor(),9    llmModel = OllamaModels.Meta.LLAMA_3_2,10) {11    install(Tracing) {12        addMessageProcessor(writer)13    }14}1516// Run the agent17agent.run(input)1819// Writer will be automatically closed when the block exits

자바

1var writer = TraceFeatureMessageFileWriter.create(2    outputPath,3    path -> { try { return Files.newOutputStream(path); } catch (IOException e) { throw new UncheckedIOException(e); }}4);56// Creating an agent7var agent = AIAgent.builder()8    .promptExecutor(PromptExecutor.builder().ollama().build())9    .llmModel(OllamaModels.Meta.LLAMA_3_2)1011    .install(Tracing.Feature, config -> {12        config.addMessageProcessor(writer);13    })14    .build();1516// Run the agent17agent.run(input);1819// Writer will be automatically closed when the block exits

파일에 대한 특정 이벤트 추적

코틀린

1val fileWriter = TraceFeatureMessageFileWriter(2    outputPath,3    { path: Path -> SystemFileSystem.sink(path).buffered() }4)56// Creating an agent7val agent = AIAgent(8    promptExecutor = simpleOllamaAIExecutor(),9    llmModel = OllamaModels.Meta.LLAMA_3_2,10) {11    install(Tracing) {12        addMessageProcessor(fileWriter)1314        // Only trace LLM calls15        fileWriter.setMessageFilter { message ->16            message is LLMCallStartingEvent || message is LLMCallCompletedEvent17        }18    }19}

자바

1var fileWriter = TraceFeatureMessageFileWriter.create(2    outputPath,3    path -> { try { return Files.newOutputStream(path); } catch (IOException e) { throw new UncheckedIOException(e); }}4);56// Creating an agent7var agent = AIAgent.builder()8    .promptExecutor(PromptExecutor.builder().ollama().build())9    .llmModel(OllamaModels.Meta.LLAMA_3_2)1011    .install(Tracing.Feature, config -> {12        config.addMessageProcessor(fileWriter);1314        // Only trace LLM calls15        fileWriter.setMessageFilter(message ->16            message instanceof LLMCallStartingEvent || message instanceof LLMCallCompletedEvent17        );18    })19    .build();

특정 이벤트를 원격 엔드포인트로 추적

네트워크를 통해 이벤트 데이터를 전송해야 하는 경우 원격 엔드포인트에 대한 추적을 사용합니다. 일단 시작되면 원격 엔드포인트는 지정된 포트 번호에서 라이트 서버를 시작하고 Kotlin 서버 전송 이벤트를 통해 이벤트를 보냅니다. (SSE).

코틀린

1val connectionConfig = DefaultServerConnectionConfig(host = host, port = port)2val writer = TraceFeatureMessageRemoteWriter(connectionConfig)34// Creating an agent5val agent = AIAgent(6    promptExecutor = simpleOllamaAIExecutor(),7    llmModel = OllamaModels.Meta.LLAMA_3_2,8) {9    install(Tracing) {10        addMessageProcessor(writer)11    }12}1314// Run the agent15agent.run(input)1617// Writer will be automatically closed when the block exits

자바

1var connectionConfig = new DefaultServerConnectionConfig(host, port);2var writer = new TraceFeatureMessageRemoteWriter(connectionConfig);34// Creating an agent5var agent = AIAgent.builder()6    .promptExecutor(PromptExecutor.builder().ollama().build())7    .llmModel(OllamaModels.Meta.LLAMA_3_2)89    .install(Tracing.Feature, config -> {10        config.addMessageProcessor(writer);11    })12    .build();1314// Run the agent15agent.run(input);1617// Writer will be automatically closed when the block exits

클라이언트 측에서는 FeatureMessageRemoteClient을 사용하여 이벤트를 수신하고 역직렬화할 수 있습니다.

코틀린

1val clientConfig = DefaultClientConnectionConfig(host = host, port = port, protocol = URLProtocol.HTTP)2val agentEvents = mutableListOf<DefinedFeatureEvent>()34val clientJob = launch {5    FeatureMessageRemoteClient(connectionConfig = clientConfig, scope = this).use { client ->6        val collectEventsJob = launch {7            client.receivedMessages.consumeAsFlow().collect { event ->8                // Collect events from server9                agentEvents.add(event as DefinedFeatureEvent)1011                // Stop collecting events on agent finished12                if (event is AgentCompletedEvent) {13                    cancel()14                }15            }16        }17        client.connect()18        collectEventsJob.join()19        client.healthCheck()20    }21}2223listOf(clientJob).joinAll()

API 문서

추적 기능은 다음과 같은 주요 구성 요소가 포함된 모듈식 아키텍처를 따릅니다.

  1. Tracing: 에이전트 파이프라인에서 이벤트를 가로채는 기본 기능 클래스입니다.
  2. TraceFeatureConfig: 기능 동작을 사용자 정의하기 위한 구성 클래스입니다.
  3. 메시지 프로세서: 추적 이벤트를 처리하고 출력하는 구성 요소: