服务器 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 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
执行一个 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."
}
]
}
}
}
会话管理
创建会话
创建一个新会话:
POST /api/sessions
请求体:
{
"appName": "my_agent",
"userId": "user123",
"sessionId": "session456"
}
响应:
{
"id": "session456",
"appName": "my_agent",
"userId": "user123",
"lastUpdateTime": 1234567890,
"events": [],
"state": {}
}
获取会话
检索会话详情:
GET /api/sessions/:app_name/:user_id/:session_id
响应:
{
"id": "session456",
"appName": "my_agent",
"userId": "user123",
"lastUpdateTime": 1234567890,
"events": [],
"state": {}
}
删除会话
删除一个会话:
DELETE /api/sessions/:app_name/:user_id/:session_id
响应:
- 状态码:
204 No Content
列出会话
列出用户的所有会话:
GET /api/apps/:app_name/users/:user_id/sessions
响应:
[
{
"id": "session456",
"appName": "my_agent",
"userId": "user123",
"lastUpdateTime": 1234567890,
"events": [],
"state": {}
}
]
工件管理
列出工件
列出会话的所有工件:
GET /api/sessions/:app_name/:user_id/:session_id/artifacts
响应:
[
"image1.png",
"document.pdf",
"data.json"
]
获取工件
下载一个工件:
GET /api/sessions/:app_name/:user_id/:session_id/artifacts/:artifact_name
响应:
- Content-Type: 由文件扩展名决定
- 正文:二进制或文本内容
应用程序管理
列出应用程序
列出所有可用的 Agent:
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/
功能
- 交互式聊天:发送消息并接收流式响应
- 会话管理:创建、查看和切换会话
- 多 Agent 支持:可视化 Agent 传输和层级结构
- 工件查看器:查看和下载会话工件
- 实时更新:基于 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
提供您自己的 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
对于生产部署,请使用持久化 Session Service:
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,允许来自任何源的请求。这适用于开发环境,但在生产环境中应加以限制。
遥测
服务器启动时会自动初始化遥测。日志以结构化格式输出到 stdout。
日志级别:
ERROR:严重错误WARN:警告INFO:一般信息(默认)DEBUG:详细调试TRACE:非常详细的跟踪
使用 RUST_LOG 环境变量设置日志级别:
RUST_LOG=debug cargo run -- serve
最佳实践
- Session Management: 在运行 agent 之前始终创建一个 session
- 错误处理: 检查 HTTP 状态码并适当地处理错误
- Streaming: 使用 SSE 进行实时响应;逐行解析事件
- 安全性: 在生产环境中,实现身份验证并限制 CORS
- 持久化: 在生产部署中使用
DatabaseSessionService - 监控: 启用 telemetry 并监控日志以发现问题
全栈示例
有关与 ADK 后端交互的前端应用程序的完整工作示例,请参见 Research Paper Generator 示例。这演示了:
- 前端: 具有实时 streaming 的 HTML/JavaScript 客户端
- 后端: 带有自定义研究和 PDF 生成 tools 的 ADK agent
- 集成: 使用 SSE streaming 的完整 REST API 用法
- Artifacts: PDF 生成和下载
- Session Management: 自动 session 创建和处理
该示例展示了使用 ADK-Rust 构建 AI 驱动的 Web 应用程序的生产就绪模式。
快速开始:
# 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
文件:
- Backend:
adk-rust-guide/examples/deployment/full_stack_research.rs - Frontend:
examples/research_paper/frontend.html - Documentation:
examples/research_paper/README.md - Architecture:
examples/research_paper/architecture.md
相关
- Launcher - 启动服务器
- Sessions - Session 管理
- Artifacts - Artifact 存储
- Observability - Telemetry 和日志
上一页: ← Launcher | 下一页: A2A Protocol →