본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Execute Agent Stream API (gRPC)

원문 보기 위키 갱신

버전 3.8 도입

gRPC Execute Agent Stream API는 protocol buffers를 gRPC로 스트리밍해 에이전트(agent) 실행을 스트리밍하기 위한 바이너리 인터페이스예요. 서버는 에이전트가 출력을 만들어내는 대로 응답 청크(chunk)를 클라이언트에 스트리밍해서, 실행이 끝나기 전에도 클라이언트가 출력 처리를 시작할 수 있어요. 대규모 언어 모델(LLM)이 토큰 단위로 출력을 만들어내는 대화형 에이전트에서 스트리밍을 사용해요.

에이전트 실행은 REST나 gRPC 중 어느 쪽으로든 스트리밍할 수 있어요. 두 전송 방식 모두 같은 점진적으로 생성된 출력을 반환하므로, 클라이언트에 더 잘 맞는 쪽을 고르면 돼요:

  • REST 스트리밍은 HTTP 위에서 server-sent events(SSE)를 사용해요. 브라우저, 표준 HTTP 클라이언트, cURL 같은 CLI 도구가 직접 지원해요. 이 기능은 실험적(experimental)이며 프로덕션 환경에서는 권장되지 않아요. 자세한 내용은 Execute Agent Stream API 문서를 참고하세요.
  • gRPC 스트리밍은 HTTP/2 위에서 protocol buffers를 사용해요. 이 전송 방식은 직렬화 오버헤드가 낮고 페이로드가 작으며, HTTP/2의 흐름 제어와 연결 다중화를 활용한 네이티브 서버 스트리밍 시맨틱을 제공하고, gRPC를 지원하는 모든 언어로 클라이언트를 생성할 수 있는 강력한 타입의 스키마를 제공해요.

스트리밍 에이전트 실행은 다음 외부 호스팅 모델을 사용하는 에이전트에서 지원돼요:

  • OpenAI Chat Completion
  • Amazon Bedrock Converse Stream

출처: OpenSearch 문서

본문

Prerequisites

gRPC Execute Agent Stream API를 사용하기 전에 다음 전제 조건을 충족했는지 확인하세요:

  • 클러스터에서 gRPC 전송을 활성화하세요. 자세한 내용은 Using gRPC APIs 문서를 참고하세요.
  • 클라이언트 쪽에서 ML Commons protobuf를 확보하세요. protobuf를 얻는 방법은 Using gRPC APIs 문서를 참고하세요.
  • 지원되는 스트리밍 모델을 사용하는 에이전트를 등록하세요. 에이전트와 커넥터 구성에 대해서는 Execute Agent Stream API 문서를 참고하세요.

gRPC service and method

gRPC Execute Agent Stream API는 MLService 서비스에 위치해요.

MLService 안의 ExecuteAgentStream 메서드를 호출해 스트리밍 에이전트 실행 요청을 제출할 수 있어요. 이 메서드는 MlExecuteAgentStreamRequest를 받아서 PredictResponse 메시지의 스트림을 반환해요.

ExecuteAgentStream은 서버 스트리밍 원격 프로시저 호출(RPC)이에요. 클라이언트는 단일 요청을 보내고, 서버는 일련의 응답 메시지를 반환해요. 마지막 메시지는 is_last를 true로 설정하고, 그다음 서버가 스트림을 닫아요.

Request fields

gRPC Execute Agent Stream API는 다음 요청 필드를 지원해요.

MlExecuteAgentStreamRequest fields

MlExecuteAgentStreamRequest 메시지는 다음 필드를 받아들여요.

| Field | Protobuf type | Required | 설명 | | agent_id | string | Required | 실행할 에이전트의 ID예요. | | ml_execute_agent_stream_request_body | MLExecuteAgentStreamRequestBody | Required | 실행 파라미터를 담은 요청 페이로드예요. |

MLExecuteAgentStreamRequestBody fields

MLExecuteAgentStreamRequestBody 메시지는 다음 필드를 받아들여요.

| Field | Protobuf type | Required | 설명 | | parameters | Parameters | Required | 에이전트에 전달되는 입력 파라미터예요. |

Parameters fields

에이전트 실행을 위해 Parameters 메시지는 다음 필드를 받아들여요.

| Field | Protobuf type | 설명 | | question | string | 에이전트로 보내는 입력 질문이에요. |

Response fields

서버는 일련의 PredictResponse 메시지를 스트리밍해요. 각 메시지는 생성된 출력의 한 청크를 담고 다음 필드를 제공해요.

| Field | Protobuf type | 설명 | | inference_results | repeated InferenceResults | 해당 청크의 추론 결과예요. | | inference_results.output | repeated Output | 각 추론 결과의 출력 객체예요. | | inference_results.output.name | string | 출력 필드의 이름(보통 response)이에요. | | inference_results.output.result | string | memory_id와 parent_interaction_id 필드의 값이에요. | | inference_results.output.data_as_map | DataAsMap | 해당 청크의 응답 내용과 메타데이터예요. | | inference_results.output.data_as_map.content | string | 청크의 텍스트 내용이에요. 전체 응답을 재구성하려면 청크별 content 값을 이어 붙이세요. | | inference_results.output.data_as_map.is_last | bool | 이 청크가 스트림의 마지막인지 여부예요. true이면 더 이상 메시지가 전송되지 않아요. |

Example request

아래 예시는 gRPC 요청 메시지의 JSON 표현이에요. agent_id와 question을 에이전트 구성에 맞는 값으로 바꾸세요:

{
"agent_id": "your_agent_id",
"ml_execute_agent_stream_request_body": {
"parameters": {
"question": "List indices in my cluster"
}
}
}

copy

아래 예시는 대화형 에이전트의 실행을 스트리밍하는 Java gRPC 클라이언트예요. 에이전트 ID와 question을 에이전트 구성에 맞는 값으로 바꾸세요:

import org.opensearch.protobufs.*;
import org.opensearch.protobufs.services.MLServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

import java.util.Iterator;

public class ExecuteAgentStreamClient {
public static void main(String[] args) {
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9400)
.usePlaintext()
.build();

// Create a gRPC stub for ML operations
MLServiceGrpc.MLServiceBlockingStub mlStub = MLServiceGrpc.newBlockingStub(channel);

// Build the request parameters for the agent
Parameters parameters = Parameters.newBuilder()
.setQuestion("List indices in my cluster")
.build();

// Create the streaming agent execution request
MlExecuteAgentStreamRequest request = MlExecuteAgentStreamRequest.newBuilder()
.setAgentId("your_agent_id")
.setMlExecuteAgentStreamRequestBody(MLExecuteAgentStreamRequestBody.newBuilder()
.setParameters(parameters)
.build())
.build();

// Execute the request and read the streamed response
try {
Iterator responses = mlStub.executeAgentStream(request);
while (responses.hasNext()) {
PredictResponse response = responses.next();
for (InferenceResults results : response.getInferenceResultsList()) {
for (Output output : results.getOutputList()) {
DataAsMap chunk = output.getDataAsMap();
System.out.print(chunk.getContent());
if (chunk.getIsLast()) {
System.out.println("\n[stream complete]");
}
}
}
}
} catch (io.grpc.StatusRuntimeException e) {
System.err.println("gRPC execute agent stream request failed with status: " + e.getStatus());
System.err.println("Error message: " + e.getMessage());
}

channel.shutdown();
}
}

copy

Example response

서버는 일련의 PredictResponse 메시지를 반환해요. 각 메시지는 content 필드에 생성된 텍스트 한 청크를 담고, 마지막 메시지는 isLast를 true로 설정해요. 아래 예시는 스트리밍된 청크의 JSON 표현이에요:

{
"inferenceResults": [
{
"output": [
{
"name": "memory_id",
"result": "6CMnkJ8BLGHoqtB13ipp"
},
{
"name": "parent_interaction_id",
"result": "6SMnkJ8BLGHoqtB13irB"
},
{
"name": "response",
"dataAsMap": {
"content": "Hello",
"isLast": false
}
}
]
}
]
}
  • Execute Agent Stream API – 에이전트 실행 스트리밍의 REST 버전
  • Using gRPC APIs – gRPC 전송 구성과 클라이언트 요구 사항

더 알아보기 (Learn more)

gRPC 스트리밍을 쓸 때는 서버 스트리밍 RPC의 동작 방식과, 응답의 content를 청크별로 이어 붙여 전체 응답을 재구성해야 한다는 점을 기억해 주세요.