Skip to main content

adk_server/agent_engine/
mod.rs

1//! Agent Engine dispatch surface for the Gemini Enterprise Agent Platform.
2//!
3//! Makes an adk-rust agent in a BYOC container drivable by
4//! `reasoningEngines.query`, `reasoningEngines.streamQuery`, the console
5//! Playground, and the platform SDKs. The host POSTs a
6//! [`DispatchRequest`] envelope naming a [`ClassMethod`]; this module routes
7//! it to the session service, memory service, or [`Runner`].
8//!
9//! - `POST /api/reasoning_engine` — unary operations, responding
10//!   `{"output": ...}`.
11//! - `POST /api/stream_reasoning_engine` — streaming operations, responding
12//!   newline-delimited JSON events with `Content-Type: application/json`
13//!   (no SSE framing).
14//!
15//! # Example
16//!
17//! ```rust,no_run
18//! use adk_server::agent_engine::{AgentEngineState, agent_engine_router};
19//! use adk_runner::Runner;
20//! use std::sync::Arc;
21//!
22//! # fn build(runner: Arc<Runner>) -> axum::Router {
23//! let state = AgentEngineState::new(runner);
24//! agent_engine_router(state)
25//! # }
26//! ```
27
28mod entrypoint;
29mod envelope;
30mod operations;
31
32#[cfg(feature = "vertex-remote-engine")]
33pub mod remote;
34
35pub use entrypoint::{AgentEngineOptions, build_agent_engine_app, serve_agent_engine};
36pub use envelope::DispatchRequest;
37pub use operations::{
38    AddSessionToMemoryInput, AgentRunRequest, ApiMode, ClassMethod, CreateSessionInput,
39    DeleteSessionInput, GetSessionInput, ListSessionsInput, SearchMemoryInput, StreamQueryInput,
40    StreamingAgentRunWithEventsInput,
41};
42
43use adk_core::{AdkError, Content, ErrorCategory, ErrorComponent, Result};
44use adk_runner::Runner;
45use axum::{
46    Json, Router,
47    body::Body,
48    http::{StatusCode, header},
49    response::{IntoResponse, Response},
50    routing::post,
51};
52use futures::StreamExt;
53use serde_json::Value;
54use std::collections::HashMap;
55use std::str::FromStr;
56use std::sync::Arc;
57use tracing::{error, info};
58
59/// Shared state for the Agent Engine dispatch handlers.
60///
61/// The session service and app name are taken from the [`Runner`] so the
62/// dispatch surface and the runner can never disagree about session scoping.
63/// The memory and artifact services are optional from day one: filling them
64/// in later is additive, mirroring adk-python `AdkApp`'s
65/// `memory_service_builder` / `artifact_service_builder`.
66#[derive(Clone)]
67pub struct AgentEngineState {
68    runner: Arc<Runner>,
69    session_service: Arc<dyn adk_session::SessionService>,
70    memory_service: Option<Arc<dyn adk_memory::MemoryService>>,
71    artifact_service: Option<Arc<dyn adk_artifact::ArtifactService>>,
72    app_name: String,
73}
74
75impl AgentEngineState {
76    /// Creates dispatch state around a prebuilt runner.
77    ///
78    /// # Example
79    ///
80    /// ```rust,no_run
81    /// use adk_server::agent_engine::AgentEngineState;
82    /// use adk_runner::Runner;
83    /// use std::sync::Arc;
84    ///
85    /// # fn build(runner: Arc<Runner>) {
86    /// let state = AgentEngineState::new(runner);
87    /// # }
88    /// ```
89    pub fn new(runner: Arc<Runner>) -> Self {
90        let session_service = runner.session_service().clone();
91        let app_name = runner.app_name().to_string();
92        Self { runner, session_service, memory_service: None, artifact_service: None, app_name }
93    }
94
95    /// Configures the memory service backing `async_add_session_to_memory`
96    /// and `async_search_memory`. Without one, both return an
97    /// [`Unsupported`](adk_core::ErrorCategory::Unsupported) error.
98    pub fn with_memory_service(
99        mut self,
100        memory_service: Arc<dyn adk_memory::MemoryService>,
101    ) -> Self {
102        self.memory_service = Some(memory_service);
103        self
104    }
105
106    /// Configures the artifact service. No class method consumes it yet; it
107    /// is carried here so wiring `GcsArtifactService` later is additive.
108    pub fn with_artifact_service(
109        mut self,
110        artifact_service: Arc<dyn adk_artifact::ArtifactService>,
111    ) -> Self {
112        self.artifact_service = Some(artifact_service);
113        self
114    }
115
116    /// The runner executing `stream_query` operations.
117    pub fn runner(&self) -> &Arc<Runner> {
118        &self.runner
119    }
120
121    /// The session service backing the session class methods.
122    pub fn session_service(&self) -> &Arc<dyn adk_session::SessionService> {
123        &self.session_service
124    }
125
126    /// The memory service, when configured.
127    pub fn memory_service(&self) -> Option<&Arc<dyn adk_memory::MemoryService>> {
128        self.memory_service.as_ref()
129    }
130
131    /// The artifact service, when configured.
132    pub fn artifact_service(&self) -> Option<&Arc<dyn adk_artifact::ArtifactService>> {
133        self.artifact_service.as_ref()
134    }
135
136    /// The resolved application name used for session scoping.
137    pub fn app_name(&self) -> &str {
138        &self.app_name
139    }
140}
141
142/// Builds the Agent Engine dispatch router.
143///
144/// Mounts `POST /api/reasoning_engine` (unary) and
145/// `POST /api/stream_reasoning_engine` (streaming). Merge it into a server
146/// app or serve it standalone in a BYOC container.
147pub fn agent_engine_router(state: AgentEngineState) -> Router {
148    Router::new()
149        .route("/api/reasoning_engine", post(dispatch_unary))
150        .route("/api/stream_reasoning_engine", post(dispatch_stream))
151        .with_state(state)
152}
153
154/// Renders an [`AdkError`] as its problem-JSON response.
155fn problem_response(err: &AdkError) -> Response {
156    let status =
157        StatusCode::from_u16(err.http_status_code()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
158    (status, Json(err.to_problem_json())).into_response()
159}
160
161/// The error for a method POSTed to the wrong endpoint (streaming method on
162/// the unary route or vice versa).
163fn wrong_endpoint(method: ClassMethod, expected: &str) -> AdkError {
164    AdkError::new(
165        ErrorComponent::Server,
166        ErrorCategory::InvalidInput,
167        "agent_engine.wrong_endpoint",
168        format!("class_method '{}' must be POSTed to {expected}", method.as_str()),
169    )
170}
171
172/// Unary dispatch: `POST /api/reasoning_engine`.
173async fn dispatch_unary(
174    axum::extract::State(state): axum::extract::State<AgentEngineState>,
175    Json(request): Json<DispatchRequest>,
176) -> Response {
177    info!(class_method = %request.class_method, "agent engine unary dispatch");
178    let method = match ClassMethod::from_str(&request.class_method) {
179        Ok(method) => method,
180        Err(err) => return problem_response(&err),
181    };
182    if method.api_mode().is_streaming() {
183        return problem_response(&wrong_endpoint(method, "/api/stream_reasoning_engine"));
184    }
185    let output = run_unary(&state, method, request.input).await;
186    match output {
187        Ok(output) => Json(envelope::unary_response(output)).into_response(),
188        Err(err) => {
189            error!(class_method = %request.class_method, error = %err, "unary dispatch failed");
190            problem_response(&err)
191        }
192    }
193}
194
195/// Executes a unary class method against the state.
196///
197/// The match is exhaustive — streaming variants are rejected before this is
198/// called, and returning an error for them here keeps the compiler enforcing
199/// that every future variant picks an endpoint.
200async fn run_unary(
201    state: &AgentEngineState,
202    method: ClassMethod,
203    input: Option<Value>,
204) -> Result<Value> {
205    match method {
206        ClassMethod::CreateSession | ClassMethod::AsyncCreateSession => {
207            operations::handle_create_session(state, operations::typed_input(input)?).await
208        }
209        ClassMethod::GetSession | ClassMethod::AsyncGetSession => {
210            operations::handle_get_session(state, operations::typed_input(input)?).await
211        }
212        ClassMethod::ListSessions | ClassMethod::AsyncListSessions => {
213            operations::handle_list_sessions(state, operations::typed_input(input)?).await
214        }
215        ClassMethod::DeleteSession | ClassMethod::AsyncDeleteSession => {
216            operations::handle_delete_session(state, operations::typed_input(input)?).await
217        }
218        ClassMethod::AsyncAddSessionToMemory => {
219            operations::handle_add_session_to_memory(state, operations::typed_input(input)?).await
220        }
221        ClassMethod::AsyncSearchMemory => {
222            operations::handle_search_memory(state, operations::typed_input(input)?).await
223        }
224        ClassMethod::RegisterOperations => Ok(operations::handle_register_operations()),
225        ClassMethod::StreamQuery
226        | ClassMethod::AsyncStreamQuery
227        | ClassMethod::StreamingAgentRunWithEvents => {
228            Err(wrong_endpoint(method, "/api/stream_reasoning_engine"))
229        }
230    }
231}
232
233/// Streaming dispatch: `POST /api/stream_reasoning_engine`.
234async fn dispatch_stream(
235    axum::extract::State(state): axum::extract::State<AgentEngineState>,
236    Json(request): Json<DispatchRequest>,
237) -> Response {
238    info!(class_method = %request.class_method, "agent engine streaming dispatch");
239    let method = match ClassMethod::from_str(&request.class_method) {
240        Ok(method) => method,
241        Err(err) => return problem_response(&err),
242    };
243    let prepared = match method {
244        ClassMethod::StreamQuery | ClassMethod::AsyncStreamQuery => {
245            prepare_stream_query(&state, request.input).await
246        }
247        ClassMethod::StreamingAgentRunWithEvents => {
248            prepare_agent_run_with_events(&state, request.input).await
249        }
250        ClassMethod::CreateSession
251        | ClassMethod::AsyncCreateSession
252        | ClassMethod::GetSession
253        | ClassMethod::AsyncGetSession
254        | ClassMethod::ListSessions
255        | ClassMethod::AsyncListSessions
256        | ClassMethod::DeleteSession
257        | ClassMethod::AsyncDeleteSession
258        | ClassMethod::AsyncAddSessionToMemory
259        | ClassMethod::AsyncSearchMemory
260        | ClassMethod::RegisterOperations => Err(wrong_endpoint(method, "/api/reasoning_engine")),
261    };
262    let (user_id, session_id, content) = match prepared {
263        Ok(prepared) => prepared,
264        Err(err) => {
265            error!(class_method = %request.class_method, error = %err, "streaming dispatch failed");
266            return problem_response(&err);
267        }
268    };
269
270    let (typed_user_id, typed_session_id) = match operations::typed_identity(&user_id, &session_id)
271    {
272        Ok(identity) => identity,
273        Err(err) => return problem_response(&err),
274    };
275    let event_stream = match state.runner().run(typed_user_id, typed_session_id, content).await {
276        Ok(stream) => stream,
277        Err(err) => {
278            error!(error = %err, "runner failed to start");
279            return problem_response(&err);
280        }
281    };
282
283    // One JSON object per line. An error after the first event cannot change
284    // the already-sent 200 status, so it is emitted as a problem-JSON line
285    // and the stream ends — the same contract as adk-python's template
286    // server, whose callers parse each line independently.
287    let body_stream = event_stream.map(|item| {
288        let line = match item {
289            Ok(event) => serde_json::to_string(&event).unwrap_or_else(|err| {
290                error_line(&AdkError::new(
291                    ErrorComponent::Server,
292                    ErrorCategory::Internal,
293                    "agent_engine.event_serialization",
294                    format!("failed to serialize event: {err}"),
295                ))
296            }),
297            Err(err) => {
298                error!(error = %err, "agent event stream failed");
299                error_line(&err)
300            }
301        };
302        Ok::<_, std::convert::Infallible>(format!("{line}\n"))
303    });
304
305    Response::builder()
306        .status(StatusCode::OK)
307        .header(header::CONTENT_TYPE, "application/json")
308        .body(Body::from_stream(body_stream))
309        .unwrap_or_else(|err| {
310            error!(error = %err, "failed to build streaming response");
311            StatusCode::INTERNAL_SERVER_ERROR.into_response()
312        })
313}
314
315/// Serializes an error as a single NDJSON problem line.
316fn error_line(err: &AdkError) -> String {
317    err.to_problem_json().to_string()
318}
319
320/// Validates a `stream_query` input and resolves its session.
321async fn prepare_stream_query(
322    state: &AgentEngineState,
323    input: Option<Value>,
324) -> Result<(String, String, Content)> {
325    let input: StreamQueryInput = operations::typed_input(input)?;
326    let content = operations::message_to_content(input.message)?;
327    let (session_id, _created) =
328        operations::resolve_session(state, &input.user_id, input.session_id, HashMap::new())
329            .await?;
330    Ok((input.user_id, session_id, content))
331}
332
333/// Validates a `streaming_agent_run_with_events` input and resolves its
334/// session, applying the request's state delta.
335async fn prepare_agent_run_with_events(
336    state: &AgentEngineState,
337    input: Option<Value>,
338) -> Result<(String, String, Content)> {
339    let input: StreamingAgentRunWithEventsInput = operations::typed_input(input)?;
340    let request: AgentRunRequest = serde_json::from_str(&input.request_json).map_err(|err| {
341        AdkError::new(
342            ErrorComponent::Server,
343            ErrorCategory::InvalidInput,
344            "agent_engine.invalid_agent_run_request",
345            format!("request_json is not a valid AgentRunRequest: {err}"),
346        )
347    })?;
348    let state_delta: HashMap<String, Value> =
349        request.state_delta.unwrap_or_default().into_iter().collect();
350    // A created session takes the delta as its initial state; an existing one
351    // gets it as an appended state-delta event, matching the REST runtime.
352    let (session_id, created) = operations::resolve_session(
353        state,
354        &request.user_id,
355        Some(request.session_id),
356        state_delta.clone(),
357    )
358    .await?;
359    if !created {
360        operations::apply_state_delta(state, &request.user_id, &session_id, state_delta).await?;
361    }
362    Ok((request.user_id, session_id, request.new_message))
363}