服务器 API

ADK-Rust 服务器提供了一个 REST API,用于运行 agents、管理 sessions 和访问 artifacts。当您使用服务器模式下的 Launcher 部署您的 agent 时,它会公开这些端点以及一个 Web UI。

概述

该服务器基于 Axum 构建,并提供:

  • REST API: 用于 agent 执行和 session 管理的 HTTP 端点
  • Server-Sent Events (SSE): agent 响应的实时流
  • Web UI: 交互式浏览器界面
  • CORS 支持: 启用跨域请求
  • Telemetry: 内置可观测性与追踪

ServerConfig 还为长期运行的部署公开了 runner 级别的直通:

let config = ServerConfig::new(agent_loader, session_service)
    .with_compaction(compaction_config)
    .with_context_cache(context_cache_config, cache_capable_model);

启动服务器

使用 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
}

从经过验证的 API 脚手架开始:

cargo adk new my-api --template api
cd my-api
cargo run

REST API 端点

健康检查

检查服务器是否正在运行:

GET /api/health

响应:

OK

运行 Agent 并流式传输

执行一个 agent 并使用 Server-Sent Events 流式传输响应:

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

列出 Sessions

列出用户的所有 sessions:

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

响应:

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

Artifact 管理

列出 Artifacts

列出 session 的所有 artifacts:

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: 由文件扩展名决定
  • Body: 二进制或文本内容

应用管理

列出 Applications

列出所有可用的 agents:

GET /api/apps
GET /api/list-apps  (legacy compatibility)

响应:

{
  "apps": [
    {
      "name": "my_agent",
      "description": "A helpful assistant"
    }
  ]
}

Web UI

服务器包含一个内置的 Web UI,可在以下地址访问:

http://localhost:8080/ui/

功能

  • 交互式聊天: 发送消息并接收流式响应
  • Session 管理: 创建、查看和切换 sessions
  • 多 Agent 支持: 可视化 agent 传输和层级结构
  • Artifact 查看器: 查看和下载 session artifacts
  • 实时更新: 基于 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
  }'

服务器配置

自定义端口

对于自定义端口,在启动生成的服务器之前设置 PORT

PORT=3000 cargo run

自定义 Artifact 服务

提供您自己的 artifact 服务:

use adk_artifact::InMemoryArtifactService;

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

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

自定义 Session 服务

对于生产部署,请使用持久化 session 服务:

use adk_session::SqliteSessionService;

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

错误处理

API 使用结构化错误响应,其 HTTP 状态码源自错误类别:

状态码类别含义
200成功
204成功 (无内容)
400invalid_input错误请求 — 无效参数或配置
401unauthorized缺少或无效的凭据
403forbidden有效凭据,权限不足
404not_found资源未找到
408timeout操作超时
429rate_limited上游速率限制超出
500internal内部服务器错误
501unsupported功能不支持
503unavailable上游服务不可用

错误响应格式 (问题 JSON):

{
  "error": {
    "code": "model.openai.rate_limited",
    "message": "OpenAI rate limit exceeded",
    "component": "model",
    "category": "rate_limited",
    "requestId": "req-abc123",
    "retryAfter": 5000,
    "upstreamStatusCode": 429
  }
}

字段 requestIdretryAfterupstreamStatusCode 在可用时包含(否则为 null)。

CORS 配置

服务器默认启用宽松的 CORS,允许来自任何源的请求。这适用于开发环境,但在生产环境中应加以限制。

遥测

服务器启动时会自动初始化遥测。日志以结构化格式输出到 stdout。

日志级别:

  • ERROR:严重错误
  • WARN:警告
  • INFO:一般信息(默认)
  • DEBUG:详细调试
  • TRACE:非常详细的跟踪

使用 RUST_LOG 环境变量设置日志级别:

RUST_LOG=debug cargo run

最佳实践

  1. 会话管理:在运行 agent 之前始终创建会话
  2. 错误处理:检查 HTTP 状态码并妥善处理错误
  3. 流式传输:使用 SSE 进行实时响应;逐行解析事件
  4. 安全性:在生产环境中,实施身份验证并限制 CORS
  5. 持久性:使用 SqliteSessionServicePostgresSessionService 用于生产部署
  6. 监控:启用遥测并监控日志以发现问题

全栈示例

对于一个完整可用的服务器脚手架,请使用经过验证的 cargo-adk API 模板。这展示了:

  • 前端:HTML/JavaScript 客户端,支持实时流式传输
  • 后端:ADK agent,带有自定义研究和 PDF 生成工具
  • 集成:完整的 REST API 用法,支持 SSE 流式传输
  • 工件:PDF 生成和下载
  • 会话管理:自动会话创建和处理

该示例展示了使用 ADK-Rust 构建 AI 驱动的 Web 应用程序的生产就绪模式。

快速开始:

cargo adk new my-api --template api
cd my-api
cargo run

文件:

  • 后端:adk-rust-guide/examples/deployment/full_stack_research.rs
  • 前端:examples/research_paper/frontend.html
  • 文档:examples/research_paper/README.md
  • 架构:examples/research_paper/architecture.md

上一页: ← 启动器 | 下一页: A2A 协议 →

服务器 API - ADK-Rust 文档 | ADK-Rust