서버 API

ADK-Rust 서버는 Agent 실행, 세션 관리 및 아티팩트 접근을 위한 REST API를 제공합니다. Launcher를 사용하여 Agent를 서버 모드로 배포할 때, 이러한 엔드포인트와 웹 UI를 노출합니다.

개요

서버는 Axum 기반으로 구축되었으며 다음 기능을 제공합니다:

  • REST API: Agent 실행 및 세션 관리를 위한 HTTP 엔드포인트
  • Server-Sent Events (SSE): Agent 응답의 실시간 스트리밍
  • Web UI: 대화형 브라우저 기반 인터페이스
  • CORS Support: 교차 출처 요청 활성화
  • Telemetry: 추적 기능이 포함된 내장된 관측 기능

서버 시작하기

Launcher를 사용하여 서버를 시작합니다:

use adk_rust::prelude::*;
use adk_rust::Launcher;
use std::sync::Arc;

#[tokio::main]
async fn main() -> Result<()> {
    let api_key = std::env::var("GOOGLE_API_KEY")?;
    let model = Arc::new(GeminiModel::new(&api_key, "gemini-2.5-flash")?);
    
    let agent = LlmAgentBuilder::new("my_agent")
        .description("A helpful assistant")
        .instruction("You are a helpful assistant.")
        .model(model)
        .build()?;
    
    Launcher::new(Arc::new(agent)).run().await
}

서버 시작:

cargo run -- serve --port 8080

REST API 엔드포인트

상태 확인

서버가 실행 중인지 확인합니다:

GET /api/health

응답:

OK

스트리밍을 통한 Agent 실행

Server-Sent Events를 사용하여 Agent를 실행하고 응답을 스트리밍합니다:

POST /api/run_sse

요청 본문:

{
  "appName": "my_agent",
  "userId": "user123",
  "sessionId": "session456",
  "newMessage": {
    "role": "user",
    "parts": [
      {
        "text": "What is the capital of France?"
      }
    ]
  },
  "streaming": true
}

응답:

  • Content-Type: text/event-stream
  • JSON 객체로 이벤트를 스트리밍합니다

이벤트 형식:

{
  "id": "evt_123",
  "timestamp": 1234567890,
  "author": "my_agent",
  "content": {
    "role": "model",
    "parts": [
      {
        "text": "The capital of France is Paris."
      }
    ]
  },
  "actions": {},
  "llm_response": {
    "content": {
      "role": "model",
      "parts": [
        {
          "text": "The capital of France is Paris."
        }
      ]
    }
  }
}

Session 관리

Session 생성

새로운 Session을 생성합니다:

POST /api/sessions

요청 본문:

{
  "appName": "my_agent",
  "userId": "user123",
  "sessionId": "session456"
}

응답:

{
  "id": "session456",
  "appName": "my_agent",
  "userId": "user123",
  "lastUpdateTime": 1234567890,
  "events": [],
  "state": {}
}

Session 가져오기

Session 상세 정보를 가져옵니다:

GET /api/sessions/:app_name/:user_id/:session_id

응답:

{
  "id": "session456",
  "appName": "my_agent",
  "userId": "user123",
  "lastUpdateTime": 1234567890,
  "events": [],
  "state": {}
}

Session 삭제

Session을 삭제합니다:

DELETE /api/sessions/:app_name/:user_id/:session_id

응답:

  • 상태: 204 No Content

Session 목록

한 User의 모든 Session을 나열합니다:

GET /api/apps/:app_name/users/:user_id/sessions

응답:

[
  {
    "id": "session456",
    "appName": "my_agent",
    "userId": "user123",
    "lastUpdateTime": 1234567890,
    "events": [],
    "state": {}
  }
]

Artifact 관리

Artifact 목록

한 Session의 모든 Artifact를 나열합니다:

GET /api/sessions/:app_name/:user_id/:session_id/artifacts

응답:

[
  "image1.png",
  "document.pdf",
  "data.json"
]

Artifact 가져오기

Artifact를 다운로드합니다:

GET /api/sessions/:app_name/:user_id/:session_id/artifacts/:artifact_name

응답:

  • Content-Type: 파일 확장자에 따라 결정됨
  • 본문: 바이너리 또는 텍스트 콘텐츠

애플리케이션 관리

애플리케이션 목록

사용 가능한 모든 Agent를 나열합니다:

GET /api/apps
GET /api/list-apps  (레거시 호환성)

응답:

{
  "apps": [
    {
      "name": "my_agent",
      "description": "도움이 되는 Assistant"
    }
  ]
}

웹 UI

서버에는 다음 주소에서 접근 가능한 내장 웹 UI가 포함되어 있습니다:

http://localhost:8080/ui/

기능

  • 인터랙티브 채팅: 메시지를 보내고 스트리밍 응답을 받습니다
  • Session 관리: Session을 생성하고, 보고, 전환합니다
  • 다중 Agent 지원: Agent 전송 및 계층 구조를 시각화합니다
  • Artifact 뷰어: Session Artifact를 보고 다운로드합니다
  • 실시간 업데이트: 즉각적인 응답을 위한 SSE 기반 스트리밍

UI 경로

  • / - /ui/로 리디렉션
  • /ui/ - 메인 채팅 인터페이스
  • /ui/assets/* - 정적 자산 (CSS, JS, 이미지)
  • /ui/assets/config/runtime-config.json - 런타임 구성

클라이언트 예시

JavaScript/TypeScript

Fetch API를 SSE와 함께 사용:

async function runAgent(message) {
  const response = await fetch('http://localhost:8080/api/run_sse', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      appName: 'my_agent',
      userId: 'user123',
      sessionId: 'session456',
      newMessage: {
        role: 'user',
        parts: [{ text: message }]
      },
      streaming: true
    })
  });

  const reader = response.body.getReader();
  const decoder = new TextDecoder();

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    
    const chunk = decoder.decode(value);
    const lines = chunk.split('\n');
    
    for (const line of lines) {
      if (line.startsWith('data: ')) {
        const event = JSON.parse(line.slice(6));
        console.log('Event:', event);
      }
    }
  }
}

Python

requests 라이브러리 사용:

import requests
import json

def run_agent(message):
    url = 'http://localhost:8080/api/run_sse'
    payload = {
        'appName': 'my_agent',
        'userId': 'user123',
        'sessionId': 'session456',
        'newMessage': {
            'role': 'user',
            'parts': [{'text': message}]
        },
        'streaming': True
    }
    
    response = requests.post(url, json=payload, stream=True)
    
    for line in response.iter_lines():
        if line:
            line_str = line.decode('utf-8')
            if line_str.startswith('data: '):
                event = json.loads(line_str[6:])
                print('Event:', event)

run_agent('What is the capital of France?')

cURL

# Create session
curl -X POST http://localhost:8080/api/sessions \
  -H "Content-Type: application/json" \
  -d '{
    "appName": "my_agent",
    "userId": "user123",
    "sessionId": "session456"
  }'

# Run agent with streaming
curl -X POST http://localhost:8080/api/run_sse \
  -H "Content-Type: application/json" \
  -d '{
    "appName": "my_agent",
    "userId": "user123",
    "sessionId": "session456",
    "newMessage": {
      "role": "user",
      "parts": [{"text": "What is the capital of France?"}]
    },
    "streaming": true
  }'

서버 설정

사용자 지정 포트

사용자 지정 포트 지정:

cargo run -- serve --port 3000

사용자 지정 Artifact Service

고유한 아티팩트 서비스를 제공하십시오:

use adk_artifact::InMemoryArtifactService;

let artifact_service = Arc::new(InMemoryArtifactService::new());

Launcher::new(Arc::new(agent))
    .with_artifact_service(artifact_service)
    .run()
    .await

사용자 지정 Session Service

프로덕션 배포의 경우, 영구적인 SessionService를 사용하십시오:

use adk_session::DatabaseSessionService;

// Note: This requires implementing a custom server setup
// The Launcher uses InMemorySessionService by default

오류 처리

API는 표준 HTTP 상태 코드를 사용합니다:

상태 코드의미
200성공
204성공 (콘텐츠 없음)
400잘못된 요청
404찾을 수 없음
500내부 서버 오류

오류 응답 형식:

{
  "error": "Error message description"
}

CORS 설정

서버는 기본적으로 허용적인 CORS를 활성화하여 모든 출처의 요청을 허용합니다. 이는 개발에 적합하지만, 프로덕션 환경에서는 제한되어야 합니다.

Telemetry

서버는 시작될 때 자동으로 Telemetry를 초기화합니다. 로그는 구조화된 형식으로 stdout에 출력됩니다.

로그 레벨:

  • ERROR: 치명적인 오류
  • WARN: 경고
  • INFO: 일반 정보 (기본값)
  • DEBUG: 상세 디버깅
  • TRACE: 매우 상세한 트레이싱

RUST_LOG 환경 변수로 로그 레벨을 설정하십시오:

RUST_LOG=debug cargo run -- serve

모범 사례

  1. 세션 관리: 항상 agent를 실행하기 전에 session을 생성합니다.
  2. 오류 처리: HTTP 상태 코드를 확인하고 오류를 적절하게 처리합니다.
  3. 스트리밍: 실시간 응답을 위해 SSE를 사용하고, 이벤트를 한 줄씩 파싱합니다.
  4. 보안: 프로덕션 환경에서는 인증을 구현하고 CORS를 제한합니다.
  5. 지속성: 프로덕션 배포에는 DatabaseSessionService를 사용합니다.
  6. 모니터링: telemetry를 활성화하고 문제를 해결하기 위해 로그를 모니터링합니다.

풀스택 예시

ADK 백엔드와 상호 작용하는 프론트엔드 애플리케이션의 완전한 작업 예시는 Research Paper Generator 예시를 참조하십시오. 이는 다음을 보여줍니다:

  • 프론트엔드: 실시간 스트리밍을 지원하는 HTML/JavaScript 클라이언트
  • 백엔드: 사용자 지정 연구 및 PDF 생성 Tool을 포함한 ADK agent
  • 통합: SSE 스트리밍을 포함한 완전한 REST API 사용
  • 아티팩트: PDF 생성 및 다운로드
  • 세션 관리: 자동 session 생성 및 처리

이 예시는 ADK-Rust를 사용하여 AI 기반 웹 애플리케이션을 구축하기 위한 프로덕션 준비 패턴을 보여줍니다.

빠른 시작:

# Start the server
cargo run --example full_stack_research -p adk-rust-guide -- serve --port 8080

# Open the frontend
open examples/research_paper/frontend.html

파일:

  • 백엔드: adk-rust-guide/examples/deployment/full_stack_research.rs
  • 프론트엔드: examples/research_paper/frontend.html
  • 문서: examples/research_paper/README.md
  • 아키텍처: examples/research_paper/architecture.md

관련 항목


이전: ← Launcher | 다음: A2A Protocol →