跳转到内容

使用 API 服务器

在 ADK 中得到支持。Python v0.1.0TypeScript v0.2.0Go v0.1.0Java v0.1.0

在部署代理程序之前,您应该先对其进行测试,以确保其能够按预期正常工作。可以使用 ADK 中提供的 API 服务器,通过 REST API 来暴露这些代理程序,从而进行编程测试和集成操作。

ADK API 服务器

启动 API 服务器

使用以下命令在 ADK API 服务器上运行您的代理程序:

adk api_server
npx adk api_server

在 Go 语言中,没有独立的(standalone)……(此处“……”指代的内容在原文中被省略了)。 adk 您应该使用 CLI(命令行界面)来执行相关操作。相反,您应该将启动程序直接嵌入到您的代理程序中。 main.go. The full.NewLauncher() **辅助工具包(Helper Bundles)** 将这些组件(包括 REST API、Web UI 以及其他功能)整合到一个单一的二进制文件中。

main.go
import (
    "google.golang.org/adk/v2/cmd/launcher"
    "google.golang.org/adk/v2/cmd/launcher/full"
)

func main() {
    // ... build your agent and config ...
    l := full.NewLauncher()
    if err := l.Execute(ctx, config, os.Args[1:]); err != nil {
        log.Fatalf("Run failed: %v\n\n%s", err, l.CommandLineSyntax())
    }
}

然后,通过传递相应的参数来启动 API 服务器。 web 和 api 命令行上的子命令:

go run agent.go web api

The web 该关键词用于激活 HTTP 服务器。 api 添加 ADK REST API; 在后台处理所有请求,并将所有路由(routes)注册到相应的系统中。 /api 默认情况下,路径前缀为空(即没有前缀)。

请确保更新端口号。

使用 Maven,编译并运行 ADK Web 服务器:

mvn compile exec:java \
 -Dexec.args="--adk.agents.source-dir=src/main/java/agents --server.port=8080"

使用 Gradle, build.gradle 或者 build.gradle.kts 构建文件(build file)的 `plugins` 部分应包含以下 Java 插件:

plugins {
    id('java')
    // other plugins
}
然后,在构建文件的其他部分(即顶层结构中),创建一个新的任务:

tasks.register('runADKWebServer', JavaExec) {
    dependsOn classes
    classpath = sourceSets.main.runtimeClasspath
    mainClass = 'com.google.adk.web.AdkWebServer'
    args '--adk.agents.source-dir=src/main/java/agents', '--server.port=8080'
}

最后,在命令行中运行以下命令:

gradle runADKWebServer

在 Java 中,Dev UI(开发用户界面)和 API 服务器是捆绑在一起提供的。

该命令会启动一个本地 Web 服务器,在该服务器上你可以运行 cURL 命令或发送 API 请求来测试你的代理程序。默认情况下,服务器运行在……(具体地址或配置信息未提供)。 http://localhost:8000.

高级用法与调试

有关所有可用端点、请求/响应格式以及调试技巧的完整参考信息(包括如何使用交互式 API 文档),请参阅…… ADK API 服务器指南 如下所示。

在本地进行测试。

在本地进行测试需要启动一个本地 Web 服务器、创建一个会话,并向您的代理发送查询。首先,请确保您位于正确的工作目录中。

对于 TypeScript 来说,你应该位于代理项目(agent project)的目录中。

parent_folder/
└── my_sample_agent/  <-- For TypeScript, run commands from here
    └── agent.py (or Agent.java or agent.ts)

启动本地服务器。

接下来,使用上述命令启动本地服务器。

输出结果应该类似于以下内容:

INFO:     Started server process [12345]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://localhost:8000 (Press CTRL+C to quit)
+-----------------------------------------------------------------------------+
| ADK Web Server started                                                      |
|                                                                             |
| For local testing, access at http://localhost:8000.                         |
+-----------------------------------------------------------------------------+
2025/01/01 00:00:00 Starting the web server: &{port:8080 ...}
2025/01/01 00:00:00 Web servers starts on http://localhost:8080
2025/01/01 00:00:00        api:  you can access API using http://localhost:8080/api
2025/01/01 00:00:00        api:      for instance: http://localhost:8080/api/list-apps

Go:默认端口及路径前缀

Go API 服务器默认使用某个端口进行通信。 8080 (不是 8000 端口),并服务于该域名下的所有 REST 端点。 /api 路径前缀的默认值。可以对其进行调整。 示例: curl 请根据以下命令进行相应的操作:

Python/TypeScript/Java Go
http://localhost:8000/list-apps http://localhost:8080/api/list-apps
http://localhost:8000/apps/… http://localhost:8080/api/apps/…
http://localhost:8000/run http://localhost:8080/api/run
http://localhost:8000/run_sse http://localhost:8080/api/run_sse

该端口号可以通过相应的设置进行更改。 -port (这个短语在标准英语中并没有明确的含义,可能是某种特定语境或非正式表达的缩写。如果需要翻译成更通用的内容,可以尝试以下几种方式:) 1. **“标记为待处理/需要注意的事项”**: *例句:* “The issue was flagged on the list as requiring immediate attention.” 2. **“在系统中被标记为异常/需要进一步检查的项”**: *例句:* “This record was flagged in the database as potentially problematic.” 3. **“在流程中被标记为需要进一步处理的步骤”**: *例句:* “This step was marked on the workflow as requiring additional verification.” 请根据实际使用场景选择最合适的翻译。 web 子命令(subcommand)及其前缀(prefix)是可以被更改的。 -path_prefix (这个短语在标准英语中并没有明确的含义,可能是某种特定语境或非正式表达的缩写。如果需要翻译成更通用的内容,可以尝试以下几种方式:) 1. **“标记为待处理/需要注意的事项”**: *例句:* “The issue was flagged on the list as requiring immediate attention.” 2. **“在系统中被标记为异常/需要进一步检查的项”**: *例句:* “This record was flagged in the database as potentially problematic.” 3. **“在流程中被标记为需要进一步处理的步骤”**: *例句:* “This step was marked on the workflow as requiring additional verification.” 请根据实际使用场景选择最合适的翻译。 api 子命令(subcommand)。例如:

go run agent.go web -port 8000 api -path_prefix ""
2025-05-13T23:32:08.972-06:00  INFO 37864 --- [ebServer.main()] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port 8080 (http) with context path '/'
2025-05-13T23:32:08.980-06:00  INFO 37864 --- [ebServer.main()] com.google.adk.web.AdkWebServer          : Started AdkWebServer in 1.15 seconds (process running for 2.877)
2025-05-13T23:32:08.981-06:00  INFO 37864 --- [ebServer.main()] com.google.adk.web.AdkWebServer          : AdkWebServer application started successfully.

您的服务器现在已经在本地运行了。请确保使用正确的配置或命令来继续操作。 端口号 在所有后续的命令中也是如此。

创建一个新的会话。

在 API 服务器仍在运行的情况下,打开一个新的终端窗口或标签页,然后使用以下命令创建一个新的会话(与代理进行通信):

curl -X POST http://localhost:8000/apps/my_sample_agent/users/u_123/sessions/s_123 \
  -H "Content-Type: application/json" \
  -d '{"key1": "value1", "key2": 42}'

让我们来详细分析一下正在发生的事情:

  • http://localhost:8000/apps/my_sample_agent/users/u_123/sessions/s_123这会为您的代理创建一个新的会话(session)。 my_sample_agent该名称指的是代理文件夹的名称;该文件夹与某个用户 ID 相关联。u_123)以及会话 ID(session ID)。s_123). 您可以替换 my_sample_agent 使用您的代理文件夹名称。您可以将其替换为其他名称。 u_123 使用特定的用户 ID; s_123 使用特定的会话 ID。
  • {"key1": "value1", "key2": 42}:这是可选的。您可以在创建会话时使用该选项来自定义代理的现有状态(以字典形式表示)。

如果会话创建成功,该方法应该会返回会话相关信息。输出结果应该类似于以下内容:

{"id":"s_123","appName":"my_sample_agent","userId":"u_123","state":{"key1":"value1","key2":42},"events":[],"lastUpdateTime":1743711430.022186}

信息

您无法使用完全相同的用户 ID 和会话 ID 创建多个会话。如果您尝试这样做,可能会收到如下类似的响应: {"detail":"Session already exists: s_123"}为了解决这个问题,你可以选择以下两种方法之一: 1. 删除该会话(例如:……) s_123),或者选择另一个会话 ID。

发送一个查询请求。

有两种方法可以通过 POST 请求将查询发送给您的代理程序: /run 或者 /run_sse routes.

  • POST http://localhost:8000/run该功能会将所有事件收集到一个列表中,并一次性返回该列表。适合大多数用户使用(如果您不确定该选择是否合适,我们建议使用此功能)。
  • POST http://localhost:8000/run_sse返回的数据格式为 “Server-Sent-Events”,这是一种事件对象的流(stream of event objects)。这种格式非常适合那些希望在事件发生后立即收到通知的用户。 /run_sse您还可以进行设置。 streaming 给……;发送到…… true 为了启用令牌级别的流式传输(token-level streaming)。

使用 /run

curl -X POST http://localhost:8000/run \
-H "Content-Type: application/json" \
-d '{
"appName": "my_sample_agent",
"userId": "u_123",
"sessionId": "s_123",
"newMessage": {
    "role": "user",
    "parts": [{
    "text": "Hey whats the weather in new york today"
    }]
}
}'

在 TypeScript 中,目前只有…… camelCase 支持字段名称(例如: appName, userId, sessionId(等等)。

如果正在使用…… /run这样,您就可以同时看到所有事件的完整输出(以列表的形式显示),其外观应该类似于以下内容:

[{"content":{"parts":[{"functionCall":{"id":"af-e75e946d-c02a-4aad-931e-49e4ab859838","args":{"city":"new york"},"name":"get_weather"}}],"role":"model"},"invocationId":"e-71353f1e-aea1-4821-aa4b-46874a766853","author":"weather_time_agent","actions":{"stateDelta":{},"artifactDelta":{},"requestedAuthConfigs":{}},"longRunningToolIds":[],"id":"2Btee6zW","timestamp":1743712220.385936},{"content":{"parts":[{"functionResponse":{"id":"af-e75e946d-c02a-4aad-931e-49e4ab859838","name":"get_weather","response":{"status":"success","report":"The weather in New York is sunny with a temperature of 25 degrees Celsius (41 degrees Fahrenheit)."}}}],"role":"user"},"invocationId":"e-71353f1e-aea1-4821-aa4b-46874a766853","author":"weather_time_agent","actions":{"stateDelta":{},"artifactDelta":{},"requestedAuthConfigs":{}},"id":"PmWibL2m","timestamp":1743712221.895042},{"content":{"parts":[{"text":"OK. The weather in New York is sunny with a temperature of 25 degrees Celsius (41 degrees Fahrenheit).\n"}],"role":"model"},"invocationId":"e-71353f1e-aea1-4821-aa4b-46874a766853","author":"weather_time_agent","actions":{"stateDelta":{},"artifactDelta":{},"requestedAuthConfigs":{}},"id":"sYT42eVC","timestamp":1743712221.899018}]

使用 /run_sse

curl -X POST http://localhost:8000/run_sse \
-H "Content-Type: application/json" \
-d '{
"appName": "my_sample_agent",
"userId": "u_123",
"sessionId": "s_123",
"newMessage": {
    "role": "user",
    "parts": [{
    "text": "Hey whats the weather in new york today"
    }]
},
"streaming": false
}'

您可以进行设置。 streaming 给……;发送到…… true 为了启用令牌级(token-level)数据流传输功能,响应内容将会被分多个部分返回给用户;输出结果应该类似于以下格式:

data: {"content":{"parts":[{"functionCall":{"id":"af-f83f8af9-f732-46b6-8cb5-7b5b73bbf13d","args":{"city":"new york"},"name":"get_weather"}}],"role":"model"},"invocationId":"e-3f6d7765-5287-419e-9991-5fffa1a75565","author":"weather_time_agent","actions":{"stateDelta":{},"artifactDelta":{},"requestedAuthConfigs":{}},"longRunningToolIds":[],"id":"ptcjaZBa","timestamp":1743712255.313043}

data: {"content":{"parts":[{"functionResponse":{"id":"af-f83f8af9-f732-46b6-8cb5-7b5b73bbf13d","name":"get_weather","response":{"status":"success","report":"The weather in New York is sunny with a temperature of 25 degrees Celsius (41 degrees Fahrenheit)."}}}],"role":"user"},"invocationId":"e-3f6d7765-5287-419e-9991-5fffa1a75565","author":"weather_time_agent","actions":{"stateDelta":{},"artifactDelta":{},"requestedAuthConfigs":{}},"id":"5aocxjaq","timestamp":1743712257.387306}

data: {"content":{"parts":[{"text":"OK. The weather in New York is sunny with a temperature of 25 degrees Celsius (41 degrees Fahrenheit).\n"}],"role":"model"},"invocationId":"e-3f6d7765-5287-419e-9991-5fffa1a75565","author":"weather_time_agent","actions":{"stateDelta":{},"artifactDelta":{},"requestedAuthConfigs":{}},"id":"rAnWGSiV","timestamp":1743712257.391317}
使用 Base64 编码的文件发送查询请求。 /run 或者 /run_sse

curl -X POST http://localhost:8000/run \
-H 'Content-Type: application/json' \
-d '{
   "appName":"my_sample_agent",
   "userId":"u_123",
   "sessionId":"s_123",
   "newMessage":{
      "role":"user",
      "parts":[
         {
            "text":"Describe this image"
         },
         {
            "inlineData":{
               "displayName":"my_image.png",
               "data":"iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAYAAAD0eNT6AAAACXBIWXMAAAsTAAALEwEAmpw...",
               "mimeType":"image/png"
            }
         }
      ]
   },
   "streaming":false
}'

信息

如果您正在使用…… /run_sse你应该能够在每个事件发生的同时就看到它。

集成(Integrations)

ADK 使用了…… 回调函数(Callbacks) 为了与第三方可观测性工具(observability tools)进行集成,这些工具能够捕获代理(agent)调用及交互的详细信息。这些数据对于理解系统行为、排查问题以及评估系统性能至关重要。

部署您的代理程序。

既然您已经验证了代理程序在本地环境中的运行情况,那么就可以继续进行代理程序的部署了。以下是一些部署代理程序的方法:

  • 部署到: Agent Runtime这是一种简单的方法,可以将您的 ADK 代理部署到 Google Cloud 上的 Agent Platform 所管理的服务器上。
  • 部署到: Cloud Run 并且可以完全控制如何利用 Google Cloud 上的无服务器(serverless)架构来扩展和管理你的代理(agents)。

交互式 API 文档

仅支持 Python 和 TypeScript。

Swagger UI 的交互式文档通过以下地址提供: /docs 仅通过 Python 和 TypeScript 的 ADK API 服务器来实现该功能。Go API 服务器并未提供相应的接口(即没有公开相关的功能或数据)。 /docs 要探索这个 Go 语言编写的 REST API,可以使用下面的端点引用,或者直接发送请求来测试该 API 的功能。 curl.

API 服务器会使用 Swagger UI 自动生成交互式的 API 文档。这是一个非常实用的工具,可以帮助你探索各个 API 端点、了解请求格式,并直接在浏览器中测试你的应用程序(agent)。

要访问这些交互式文档,请启动 API 服务器,然后导航到相应页面。 http://localhost:8000/docs 在您的网页浏览器中。

您将看到一个完整且交互式的列表,其中列出了所有可用的 API 端点。您可以点击这些端点来查看有关参数、请求体以及响应结构的详细信息。此外,您还可以点击“尝试使用”(Try it out),向正在运行的代理发送实时请求。

API 端点

以下部分详细介绍了用于与您的代理(agents)进行交互的主要接口(endpoints)。

JSON命名规范

  • 请求(Request)和响应(Response)的正文数据(body)都包含相关内容。 将使用 camelCase 对于字段名称(例如, "appName").

实用功能端点(Utility endpoints)

列出可用的代理(agents)。

返回服务器发现的所有代理应用程序的列表。

  • 方法: GET
  • 路径: /list-apps

示例请求:

curl -X GET http://localhost:8000/list-apps

示例响应

["my_sample_agent", "another_agent"]


会话管理

会话(Sessions)记录了特定用户与代理(agent)交互过程中的状态信息及事件历史记录。

更新会话(Session)

更新现有的会话。

ADK Go 从版本 2.4.0 开始支持该 API 端点(即该接口)。 stateDelta 请求正文中的字段只能用于修改会话范围内的键(即那些仅在该会话中有效的键);如果尝试修改会话范围之外的键,服务器会返回 HTTP 400 错误响应。 stateDelta “changes a key” (表示“更改一个键”) “with the” (表示“使用……”或“与……一起”) app:, user:,或 temp: prefix.

  • 方法: PATCH
  • 路径: /apps/{app_name}/users/{user_id}/sessions/{session_id}

请求体(Request Body)

{
  "stateDelta": {
    "key1": "value1",
    "key2": 42
  }
}

示例请求:

curl -X PATCH http://localhost:8000/apps/my_sample_agent/users/u_123/sessions/s_abc \
  -H "Content-Type: application/json" \
  -d '{"stateDelta":{"visit_count": 5}}'

示例响应

{"id":"s_abc","appName":"my_sample_agent","userId":"u_123","state":{"visit_count":5},"events":[],"lastUpdateTime":1743711430.022186}

获取一个会话(session)。

检索特定会话的详细信息,包括其当前状态以及所有相关的事件。

  • 方法: GET
  • 路径: /apps/{app_name}/users/{user_id}/sessions/{session_id}

示例请求:

curl -X GET http://localhost:8000/apps/my_sample_agent/users/u_123/sessions/s_abc

示例响应

{"id":"s_abc","appName":"my_sample_agent","userId":"u_123","state":{"visit_count":5},"events":[...],"lastUpdateTime":1743711430.022186}

删除会话

删除一个会话及其所有相关数据。

  • 方法: DELETE
  • 路径: /apps/{app_name}/users/{user_id}/sessions/{session_id}

示例请求:

curl -X DELETE http://localhost:8000/apps/my_sample_agent/users/u_123/sessions/s_abc

示例响应 成功的删除操作不会返回任何会话数据(session data)。Python 会相应地处理这一情况(即不会返回任何结果)。 200 OK 使用(with a) null `body`: TypeScript 的返回类型是……(具体返回类型需要根据上下文来确定)。 204 No Content 状态码(Status Code):Go 语言在处理请求或执行操作后会返回相应的状态码,以表示操作的结果或发生的错误。 200 OK (内容为空。)


代理执行(Agent execution)

这些端点用于向代理发送新消息并获取响应。

运行代理程序(返回单个响应结果)

执行代理程序,并在运行完成后将所有生成的事件以单个 JSON 数组的形式返回。

  • 方法: POST
  • 路径: /run

请求体(Request Body)

{
  "appName": "my_sample_agent",
  "userId": "u_123",
  "sessionId": "s_abc",
  "newMessage": {
    "role": "user",
    "parts": [
      { "text": "What is the capital of France?" }
    ]
  }
}

在 TypeScript 中,目前只有…… camelCase 支持字段名称(例如: appName, userId, sessionId(等等)。

示例请求:

curl -X POST http://localhost:8000/run \
  -H "Content-Type: application/json" \
  -d '{
    "appName": "my_sample_agent",
    "userId": "u_123",
    "sessionId": "s_abc",
    "newMessage": {
      "role": "user",
      "parts": [{"text": "What is the capital of France?"}]
    }
  }'

运行代理程序(流式传输)

执行代理程序,并在事件生成时将其实时流式传输回客户端。 服务器发送的事件(Server-Sent Events,简称 SSE).

  • 方法: POST
  • 路径: /run_sse

请求体(Request Body) 请求体与之前的请求体相同。 /run(产品名称)……,还包含一个可选的附加组件。 streaming flag.

{
  "appName": "my_sample_agent",
  "userId": "u_123",
  "sessionId": "s_abc",
  "newMessage": {
    "role": "user",
    "parts": [
      { "text": "What is the weather in New York?" }
    ]
  },
  "streaming": true
}
- streaming:(可选)设置为 true 为了启用模型响应的令牌级(token-level)流式传输功能,该选项默认设置为……(具体设置内容需根据实际文档或代码来确定)。 false.

示例请求:

curl -X POST http://localhost:8000/run_sse \
  -H "Content-Type: application/json" \
  -d '{
    "appName": "my_sample_agent",
    "userId": "u_123",
    "sessionId": "s_abc",
    "newMessage": {
      "role": "user",
      "parts": [{"text": "What is the weather in New York?"}]
    },
    "streaming": false
  }'