Files
Agent-Docs/ADKLearning/google-adk-tutorial/code/deploy_demo.py
Nelson 514723dbe7 init
2026-04-06 12:36:04 +08:00

202 lines
5.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
Google ADK 部署配置完整示例
展示各种部署方式的配置
对应教程第09章 - 部署指南
"""
# 导入 ADK 核心模块
from google.adk.agents import Agent # Agent 类
from google.adk.tools import google_search # Google 搜索工具
# ========================================
# 定义 Agent部署入口
# ========================================
def get_weather(city: str) -> dict:
"""
获取天气信息
Args:
city (str): 城市名称
Returns:
dict: 天气信息
"""
weather_data = { # 天气数据
"北京": {"temp": "25°C", "condition": "晴天"},
"上海": {"temp": "28°C", "condition": "多云"},
}
data = weather_data.get(city) # 查找数据
if not data: # 如果找不到
return {"status": "error", "error_message": f"未找到'{city}'的天气信息"}
return {"status": "success", "city": city, **data} # 返回天气
# root_agent 是 ADK 的入口点
# 部署时 ADK 会自动查找这个变量
root_agent = Agent(
name="deploy_agent", # Agent 名称
model="gemini-2.0-flash", # 模型
description="部署演示 Agent。", # 描述
instruction=( # 系统指令
"你是一个多功能助手。\n"
"可以查询天气和搜索信息。\n"
"使用中文回答。"
),
tools=[get_weather, google_search], # 注册工具
)
# ========================================
# 以下为部署配置参考
# ========================================
# ----------------------------------------
# Dockerfile 内容(保存为 Dockerfile
# ----------------------------------------
"""
# 使用 Python 3.11 作为基础镜像
FROM python:3.11-slim
# 设置工作目录
WORKDIR /app
# 设置环境变量
ENV PYTHONUNBUFFERED=1
# 复制依赖文件
COPY requirements.txt .
# 安装依赖
RUN pip install --no-cache-dir -r requirements.txt
# 复制 Agent 代码
COPY deploy_demo.py .
# 暴露端口
EXPOSE 8080
# 启动 API Server
CMD ["adk", "api_server", "--port", "8080", "--host", "0.0.0.0"]
"""
# ----------------------------------------
# requirements.txt 内容
# ----------------------------------------
"""
google-adk>=1.0.0
"""
# ----------------------------------------
# start.sh 启动脚本
# ----------------------------------------
"""
#!/bin/bash
# ADK Agent 启动脚本
# 从环境变量读取 API Key
export GOOGLE_API_KEY="${GOOGLE_API_KEY}"
# 启动 API Server
adk api_server \\
--port 8080 \\
--host 0.0.0.0
"""
# ----------------------------------------
# docker-compose.yml 内容
# ----------------------------------------
"""
version: '3.8'
services:
adk-agent:
build: .
ports:
- "8080:8080"
environment:
- GOOGLE_API_KEY=${GOOGLE_API_KEY}
restart: unless-stopped
"""
# ----------------------------------------
# 部署命令参考
# ----------------------------------------
"""
# 构建镜像
docker build -t my-adk-agent .
# 运行容器
docker run -d \\
--name my-agent \\
-p 8080:8080 \\
-e GOOGLE_API_KEY="your_api_key" \\
my-adk-agent
# 使用 adk deploy 部署到 Cloud Run
adk deploy . --platform cloud-run
# 使用 adk deploy 部署到 Vertex AI
adk deploy . --platform vertex-ai
"""
# ========================================
# API 调用示例
# ========================================
def api_call_example():
"""
调用 ADK API Server 的示例代码
需要先启动 API Server: adk api_server --port 8080
"""
import requests # HTTP 请求库
import json # JSON 处理
API_BASE = "http://localhost:8080" # API 地址
APP_NAME = "deploy_agent" # 应用名称
USER_ID = "user_001" # 用户 ID
SESSION_ID = "session_001" # 会话 ID
# 创建会话
session_url = f"{API_BASE}/apps/{APP_NAME}/users/{USER_ID}/sessions"
response = requests.post( # 发送请求
session_url, # URL
json={"session_id": SESSION_ID}, # 请求体
)
print(f"会话创建: {response.json()}") # 打印结果
# 发送消息
run_url = f"{session_url}/{SESSION_ID}:run"
payload = { # 请求体
"user_id": USER_ID, # 用户 ID
"session_id": SESSION_ID, # 会话 ID
"new_message": { # 新消息
"role": "user", # 角色
"parts": [{"text": "北京天气怎么样?"}], # 内容
},
}
response = requests.post( # 发送请求
run_url, # URL
json=payload, # 请求体
stream=True, # 流式响应
)
for line in response.iter_lines(): # 逐行读取
if line: # 如果有内容
data = json.loads(line) # 解析 JSON
print(f"事件: {data}") # 打印事件
if __name__ == "__main__":
print("✅ 部署配置示例") # 打印信息
print("请参考文件中的注释配置部署。") # 提示
print("\n快速启动命令:") # 打印命令
print(" adk api_server --port 8080 # 启动 API Server")
print(" adk web --port 8000 # 启动 Web UI")
print(" adk deploy . --platform cloud-run # 部署到 Cloud Run")