A2A 클라이언트

·3분 읽기

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

A2A 클라이언트

A2A 클라이언트를 사용하면 네트워크를 통해 A2A 호환 에이전트와 통신할 수 있습니다. 이는 다음의 완전한 구현을 제공합니다. A2A protocol specification, 에이전트 검색 처리, 메시지 교환, 작업 관리 및 실시간 스트리밍 응답.

종속성

프로젝트에서 A2A 클라이언트를 사용하려면 build.gradle.kts에 다음 종속성을 추가하세요.

1dependencies {2    // Core A2A client library3    implementation("ai.koog:a2a-client:$koogVersion")45    // HTTP JSON-RPC transport (most common)6    implementation("ai.koog:a2a-transport-client-jsonrpc-http:$koogVersion")78    // Ktor client engine (choose one that fits your needs)9    implementation("io.ktor:ktor-client-cio:$ktorVersion")10}

개요

A2A 클라이언트는 애플리케이션과 A2A 호환 에이전트 사이의 브리지 역할을 합니다. 프로토콜 준수를 유지하고 강력한 세션을 제공하는 동시에 전체 통신 수명주기를 조율합니다. 관리.

핵심 구성요소

A2A클라이언트

완전한 A2A 프로토콜을 구현하는 기본 클라이언트 클래스입니다. 이는 다음과 같은 중앙 조정자 역할을 합니다.

  • 플러그인형 확인자를 통해 연결 및 에이전트 검색을 관리합니다.
  • 조정 메시지 교환 및 자동 프로토콜 준수를 통한 작업 운영
  • 처리 상담사가 지원하는 경우 스트리밍 응답 및 실시간 커뮤니케이션
  • 제공 강력한 애플리케이션을 위한 포괄적인 오류 처리 및 대체 메커니즘

A2AClient은 두 가지 필수 매개변수를 허용합니다.

  • ClientTransport 네트워크 통신 계층을 처리합니다.
  • 에이전트 검색 및 메타데이터 검색을 처리하는 AgentCardResolver

A2AClient 인터페이스는 A2A 에이전트와 상호 작용하기 위한 몇 가지 주요 방법을 제공합니다.

  • connect 방법 - 에이전트에 연결하고 해당 기능을 검색하여 에이전트가 수행할 수 있는 작업과 AgentCard를 캐시합니다.
  • sendMessage 방법 - 에이전트에게 메시지를 보내고 간단한 요청-응답에 대한 단일 응답을 받음 패턴
  • sendMessageStreaming 메서드 - 흐름을 반환하는 실시간 응답에 대한 스트리밍 지원을 사용하여 메시지를 보냅니다. 부분 메시지 및 작업 업데이트를 포함한 이벤트
  • getTask 메서드 - 특정 작업의 상태 및 세부 정보를 쿼리합니다.
  • cancelTask 메서드 - 에이전트가 취소를 지원하는 경우 실행 중인 작업을 취소하려면
  • cachedAgentCard 방법 - 네트워크 요청을 하지 않고 캐시된 에이전트 카드를 가져오려면 다음과 같은 경우 null을 반환합니다. connect가 아직 호출되지 않았습니다.

클라이언트수송

ClientTransport 인터페이스는 A2A 클라이언트가 프로토콜을 관리하는 동안 낮은 수준의 네트워크 통신을 처리합니다. 논리. 전송 관련 세부 정보를 추상화하여 다양한 프로토콜을 원활하게 사용할 수 있습니다.

HTTP JSON-RPC 전송

A2A 에이전트의 가장 일반적인 전송은 다음과 같습니다.

1val transport = HttpJSONRPCClientTransport(2    url = "https://agent.example.com/a2a",        // Agent endpoint URL3    httpClient = HttpClient(CIO) {                // Optional: custom HTTP client4        install(ContentNegotiation) {5            json()6        }7        install(HttpTimeout) {8            requestTimeoutMillis = 300009        }10    }11)

AgentCardResolver

AgentCardResolver 인터페이스는 에이전트 메타데이터 및 기능을 검색합니다. 다양한 소스에서 에이전트 검색이 가능하고 최적의 성능을 위한 캐싱 전략을 지원합니다.

URL 에이전트 카드 확인자

A2A 규칙에 따라 HTTP 엔드포인트에서 에이전트 카드를 가져옵니다.

1val agentCardResolver = UrlAgentCardResolver(2    baseUrl = "https://agent.example.com",           // Base URL of the agent service3    path = "/.well-known/agent-card.json",           // Standard agent card location4    httpClient = HttpClient(CIO),                    // Optional: custom HTTP client5)

빠른 시작

1. 클라이언트 생성

전송 및 에이전트 카드 확인자를 정의하고 클라이언트를 생성합니다.

1// HTTP JSON-RPC transport2val transport = HttpJSONRPCClientTransport(3    url = "https://agent.example.com/a2a"4)56// Agent card resolver7val agentCardResolver = UrlAgentCardResolver(8    baseUrl = "https://agent.example.com",9    path = "/.well-known/agent-card.json"10)1112// Create client13val client = A2AClient(transport, agentCardResolver)

2. 연결하고 발견하세요

에이전트에 연결하고 카드를 검색하세요. 에이전트 카드가 있으면 해당 기능을 쿼리하고 다른 작업(예: 에이전트 카드가 있는지 확인)을 수행할 수 있습니다. 스트리밍을 지원합니다.

1// Connect and retrieve agent capabilities2client.connect()3val agentCard = client.cachedAgentCard()45println("Connected to: ${agentCard.name}")6println("Supports streaming: ${agentCard.capabilities.streaming}")

3. 메시지 보내기

에이전트에게 메시지를 보내고 단일 응답을 받습니다. 응답은 에이전트가 직접 응답한 경우 메시지일 수도 있고 에이전트가 작업을 수행하는 경우 작업 이벤트일 수도 있습니다. 작업.

1val message = Message(2    messageId = UUID.randomUUID().toString(),3    role = Role.User,4    parts = listOf(TextPart("Hello, agent!")),5    contextId = "conversation-1"6)78val request = Request(data = MessageSendParams(message))9val response = client.sendMessage(request)1011// Handle response12when (val event = response.data) {13    is Message -> {14        val text = event.parts15            .filterIsInstance<TextPart>()16            .joinToString { it.text }17        print(text) // Stream partial responses18    }19    is TaskEvent -> {20        if (event.final) {21            println("\nTask completed")22        }23    }24}

4. 메시지 스트리밍 보내기

A2A 클라이언트는 실시간 통신을 위한 스트리밍 응답을 지원합니다. 단일 응답을 받는 대신 메시지 및 작업 업데이트를 포함한 이벤트의 Flow을 반환합니다.

1// Check if agent supports streaming2if (client.cachedAgentCard()?.capabilities?.streaming == true) {3    client.sendMessageStreaming(request).collect { response ->4        when (val event = response.data) {5            is Message -> {6                val text = event.parts7                    .filterIsInstance<TextPart>()8                    .joinToString { it.text }9                print(text) // Stream partial responses10            }11            is TaskStatusUpdateEvent -> {12                if (event.final) {13                    println("\nTask completed")14                }15            }16        }17    }18} else {19    // Fallback to non-streaming20    val response = client.sendMessage(request)21    // Handle single response22}

5. 작업 관리

A2A 클라이언트는 상태를 요청하고 취소하여 서버 작업을 제어하는 ​​방법을 제공합니다.

1// Query task status2val taskRequest = Request(data = TaskQueryParams(taskId = "task-123"))3val taskResponse = client.getTask(taskRequest)4val task = taskResponse.data56println("Task state: ${task.status.state}")78// Cancel running task9if (task.status.state == TaskState.Working) {10    val cancelRequest = Request(data = TaskIdParams(taskId = "task-123"))11    val cancelledTask = client.cancelTask(cancelRequest).data12    println("Task cancelled: ${cancelledTask.status.state}")13}