1mod 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#[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 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 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 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 pub fn runner(&self) -> &Arc<Runner> {
118 &self.runner
119 }
120
121 pub fn session_service(&self) -> &Arc<dyn adk_session::SessionService> {
123 &self.session_service
124 }
125
126 pub fn memory_service(&self) -> Option<&Arc<dyn adk_memory::MemoryService>> {
128 self.memory_service.as_ref()
129 }
130
131 pub fn artifact_service(&self) -> Option<&Arc<dyn adk_artifact::ArtifactService>> {
133 self.artifact_service.as_ref()
134 }
135
136 pub fn app_name(&self) -> &str {
138 &self.app_name
139 }
140}
141
142pub 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
154fn 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
161fn 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
172async 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
195async 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
233async 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 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
315fn error_line(err: &AdkError) -> String {
317 err.to_problem_json().to_string()
318}
319
320async 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
333async 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 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}