ADK API 服务器用于智能体本地测试与部署
ADK 提供的 API 服务器可将智能体以 REST API 形式暴露,便于在部署前进行程序化测试与集成。文中说明了启动本地服务器、创建会话并发送查询的流程,以及 Swagger UI 文档和第三方可观测性集成的用法。
## 使用 API 服务器[¶](<https://adk.dev/runtime/api-server/#use-the-api-server>) 支持于 ADKPython v0.1.0TypeScript v0.2.0Go v0.1.0Java v0.1.0 中 在部署代理之前,您应该测试它以确保它如预期的那样工作. 使用API在ADK中的AIHUBX服务器通过REST API暴露您的代理,用于程序测试和集成.  ## 启动 API 服务器[¶](<https://adk.dev/runtime/api-server/#start-the-api-server>) 使用以下命令在 ADK API 服务器中运行您的代理 : PythonTypeScriptGoJava ``` adk api_server ``` ``` npx adk api_server ``` 在吴哥,没有独立的 `adk` CLI 相反,你直接将发射器嵌入你的代理商 `main.go`。该数字 `full.NewLauncher()` 帮助器将 REST API, Web UI 等模式捆绑成一个单一的二进制 : 主语. 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 ``` 那个... `web` 关键词激活HTTP服务器. `api` 添加 ADK REST API 后端,并注册所有路由下 `/api` 默认路径前缀。 确保更新端口号码 。 MavenGradle 与 Maven 一起编译并运行 ADK 网络服务器 : ``` mvn compile exec:java \ -Dexec.args="--adk.agents.source-dir=src/main/java/agents --server.port=8080" ``` 与Gradle,那个... `build.gradle` 或 时 间 `build.gradle.kts` 构建文件应该在其插件部分有以下 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' } ``` 最后,在命令线上运行以下命令: 1. ``` gradle runADKWebServer ``` 在Java中,Dev UI和API服务器都被捆绑在一起. 此命令将启动本地网络服务器, 您可以运行 cURL 命令或发送 API 请求来测试您的代理。 默认情况下, 服务器会运行到 `http://localhost:8000`. 高级使用和调试 关于所有可用的端点、请求/答复格式和调试提示(包括如何使用交互式API文档)的完整参考,请参见: **ADK API 服务器指南** 现列于下。 ## 本地测试[¶](<https://adk.dev/runtime/api-server/#test-locally>) 本地测试涉及启动本地网络服务器, 创建会话, 并向您的代理服务器发送查询。 首先, 确保您在正确的工作目录中 。 对于TypeScript,您应该位于代理项目目录本身. ``` parent_folder/ └── my_sample_agent/ <-- For TypeScript, run commands from here └── agent.py (or Agent.java or agent.ts) ``` **启动本地服务器** 接下来,使用上面列出的命令启动本地服务器. 产出应与下列产出相似: PythonTypeScriptGoJava ``` 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 API 服务器默认端口 **8080** (不是8000),并服务于REST的所有端点下方. **`/api`** 路径前缀默认。调整所有示例 `curl` 命令如下: | Python/TypeScript/Java | 滚开 | | --- | --- | | `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` 旗帜上 `web` 子命令和前缀可以随 `-path_prefix` 旗帜上 `api` 子命令。例如: ``` 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`: 这将为您的代理创建新会话 `my_sample_agent`,它是代理文件夹的名称,用于用户 ID (`u_123`)和一届会议(ID)`s_123`。您可以替换 `my_sample_agent` 您可以替换代理文件夹的名称。 `u_123` 与特定的用户 ID ,以及 `s_123` 带有特定会话 ID . - `{"key1": "value1", "key2": 42}`: 这是可选的。 您可以在创建会话时使用它来自定义代理商的先前状态( dict) 。 如果成功创建了会话信息, 则应返回。 输出应该与 : ``` {"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"}`。要解决这个问题,可以删除该会话(例如, `s_123`),或选择不同的会话 ID. **发送查询** 有两种方式可以通过POST向您的代理发送询问,通过 `/run` 或 时 间 `/run_sse` 路线。 - `POST http://localhost:8000/run`: 将所有事件作为列表收集, 并同时返回全部列表。 适合大多数用户( 如果您不确定, 我们建议使用此列表 ) 。 - `POST http://localhost:8000/run_sse`: 返回为 Server- Sent- Events, 这是事件对象的流。 适合那些想要在事件可用后立即得到通知的人 。 with `/run_sse`,您也可以设置 `streaming` 改为: `true` 以启用符号级流。 **使用( E) `/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`(见A/CN.9/WG.III/WP.1号文件)。 如果使用的话 `/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}] ``` **使用( E) `/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` 以启用符位流,这意味着响应会以多个块返回到您,并且输出应该出现类似: ``` 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`中,您应该看到每个事件一旦得到它。 ## 一体化[¶](<https://adk.dev/runtime/api-server/#integrations>) ADK 用途 [回拨](<https://adk.dev/callbacks/>) 与第三方可观察性工具进行整合。这些集成性捕捉了代理调用和互动的详细痕迹,这对于理解行为、调试问题和评估性能至关重要。 - [奥皮克彗星](<https://github.com/comet-ml/opik>) 是一个开源的 LLM 可观察性和评价平台, [本地支持 ADK 软件](<https://www.comet.com/docs/opik/tracing/integrations/adk>). ## 部署你的特工[¶](<https://adk.dev/runtime/api-server/#deploy-your-agent>) 现在你已经核实了你的特工的本地行动, 你准备继续部署你的特工! - 部署到 [代理运行时间](<https://adk.dev/deploy/agent-runtime/>)一个简单的方法,将你的ADK代理 部署到谷歌云上的代理平台上的管理服务。 - 部署到 [云运行](<https://adk.dev/deploy/cloud-run/>) 并完全控制您如何使用Google Cloud上的无服务器架构来放大和管理您的代理商. ## 交互式 API 文件[¶](<https://adk.dev/runtime/api-server/#interactive-api-docs>) 仅限 Python 和 TypeScript Swagger UI 交互式文档服务于 `/docs` 仅由 Python 和 TypeScript ADK API 服务器使用. Go API 服务器不暴露一个 `/docs` 端点 。 要探索 Go REST API, 请使用下面的端点引用或直接发送请求 。 `curl`. API 服务器使用 Swagger UI 自动生成交互式的 API 文档。 这是探索端点,理解请求格式,以及直接从浏览器测试您的代理工具的宝贵工具 。 要访问交互式文档,请在您的网页浏览器中启动 API 服务器并导航到 http://localhost:8000/docs 。 您将会看到一个完整,交互式的列表, 列出所有可用的 API 端点, 您可以扩展该列表来查看关于参数, 请求机构, 和响应策略的详细信息 。 您甚至可以点击“ Try it out” 向运行的代理发送直播请求 。 ## API 终点[¶](<https://adk.dev/runtime/api-server/#api-endpoints>) 以下各节详细列出与您的特工进行互动的主要终点. JSON 命名公约 - **请求和答复机构** 将使用 `camelCase` 用于字段名称(例如, `"appName"`). ### 工具端点[¶](<https://adk.dev/runtime/api-server/#utility-endpoints>) #### 列出可用的代理商[¶](<https://adk.dev/runtime/api-server/#list-available-agents>) 返回服务器发现的所有代理应用程序列表 。 - **方法 :** `GET` - **路径 :** `/list-apps` **示例请求** ``` curl -X GET http://localhost:8000/list-apps ``` **示例答复** ``` ["my_sample_agent", "another_agent"] ``` --- ### 会话管理[¶](<https://adk.dev/runtime/api-server/#session-management>) 会话存储状态和事件历史,用于特定用户与代理的交互. #### 更新会话[¶](<https://adk.dev/runtime/api-server/#update-a-session>) 更新现有会话。 ADK Go在v2.4.0及更高版本中服务于此端点. `stateDelta` 字段在请求正文中只能更改会话范围键;服务器返回HTTP400若为 `stateDelta` 随密钥更改 `app:`, `user:`,或 `temp:` 前缀。 - **方法 :** `PATCH` - **路径 :** `/apps/{app_name}/users/{user_id}/sessions/{session_id}` **请求正文** ``` { "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} ``` #### 得到一个会话[¶](<https://adk.dev/runtime/api-server/#get-a-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} ``` #### 删除会话[¶](<https://adk.dev/runtime/api-server/#delete-a-session>) 删除会话及其所有相关数据。 - **方法 :** `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 ``` **示例答复** 成功删除返回无会话数据。 Python 返回 `200 OK` 带一个 `null` 。 TypeScript 返回 a `204 No Content` 状态代码。 返回 `200 OK` 以空无体. --- ### 代理执行[¶](<https://adk.dev/runtime/api-server/#agent-execution>) 这些端点用于向代理发送新消息并获得响应. #### 运行代理( 单一响应)[¶](<https://adk.dev/runtime/api-server/#run-agent-single-response>) 执行代理并返回运行完成后在单个的JSON阵列中所有生成的事件. - **方法 :** `POST` - **路径 :** `/run` **请求正文** ``` { "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`(见A/CN.9/WG.III/WP.1号文件)。 **示例请求** ``` 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?"}] } }' ``` #### 运行代理( 流线)[¶](<https://adk.dev/runtime/api-server/#run-agent-streaming>) 执行代理和流事件返回客户端,因为这些事件是使用 [服务器事件( SSE )](<https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events>). - **方法 :** `POST` - **路径 :** `/run_sse` **请求正文** 请求机构与 `/run`,并附加一个可选 `streaming` 旗帜。 ``` { "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` 以启用用于模型响应的符号级流。默认为 `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 }' ```
查看原始来源