1#![forbid(unsafe_code)]
35#![cfg_attr(docsrs, feature(doc_cfg))]
36#![cfg_attr(
37 test,
38 allow(
39 clippy::expect_used,
40 clippy::panic,
41 clippy::unwrap_used,
42 clippy::unreachable
43 )
44)]
45
46mod busy;
47mod history;
48
49use std::convert::Infallible;
50use std::future::Future;
51use std::net::SocketAddr;
52use std::sync::Arc;
53use std::time::Duration;
54
55use axum::Json;
56use axum::extract::{DefaultBodyLimit, State};
57use axum::http::{HeaderMap, StatusCode, header};
58use axum::response::sse::{Event, Sse};
59use axum::response::{IntoResponse, Response};
60use axum::routing::{get, post};
61use futures::StreamExt;
62use rig_agent::Agent;
63use rig_agent::agent::MultiTurnStreamItem;
64use rig_core::message::Message;
65use rig_core::streaming::{Item, StreamEvent};
66use rig_core::wasm_compat::{WasmCompatSend, WasmCompatSync};
67use rig_memory::AsyncStore;
68use rig_memory::recent::{Recent, TokenBudget, view};
69use serde::Deserialize;
70use serde_json::json;
71use tokio::sync::mpsc;
72use tokio::sync::{OwnedSemaphorePermit, Semaphore};
73use tracing::Instrument;
74
75use crate::busy::Busy;
76use crate::history::{
77 HistoryError, HistoryStore, InMemory, Persistent, Retained, Summarizing, is_summary, local_id,
78 summarize,
79};
80
81pub const SESSION_HEADER: &str = "x-amzn-bedrock-agentcore-runtime-session-id";
83
84pub const DEFAULT_PORT: u16 = 8080;
86
87pub const DEFAULT_MAX_SESSIONS: usize = 1000;
91
92pub const DEFAULT_HISTORY_TOKENS: usize = 32_000;
94
95pub const DEFAULT_MAX_REQUEST_BYTES: usize = 2 * 1024 * 1024;
98
99pub use busy::BusyGuard;
100pub use rig_memory;
102
103#[derive(Debug, thiserror::Error)]
105#[non_exhaustive]
106pub enum ServeError {
107 #[error("could not listen on {address}: {source}")]
109 Bind {
110 address: SocketAddr,
112 #[source]
114 source: std::io::Error,
115 },
116 #[error("serving failed: {0}")]
118 Serve(#[source] std::io::Error),
119}
120
121#[derive(Clone)]
123pub struct AgentCoreApp {
124 inner: Arc<Inner>,
125}
126
127#[derive(Clone)]
128struct Inner {
129 agent: Agent,
130 history: Arc<dyn HistoryStore>,
131 window: Arc<dyn Recent>,
132 summarizing: Option<Summarizing>,
133 record_content: bool,
134 slots: Option<Arc<Semaphore>>,
135 max_run: Option<Duration>,
136 max_request_bytes: usize,
137 busy: Arc<Busy>,
138}
139
140impl AgentCoreApp {
141 pub fn new(agent: Agent) -> Self {
143 Self {
144 inner: Arc::new(Inner {
145 agent,
146 history: Arc::new(InMemory::new(DEFAULT_MAX_SESSIONS)),
147 window: Arc::new(TokenBudget::new(DEFAULT_HISTORY_TOKENS)),
148 summarizing: None,
149 record_content: false,
150 slots: None,
151 max_run: None,
152 max_request_bytes: DEFAULT_MAX_REQUEST_BYTES,
153 busy: Busy::new(),
154 }),
155 }
156 }
157
158 #[must_use]
162 pub fn max_sessions(self, max: usize) -> Self {
163 self.rebuild(|inner| inner.history = Arc::new(InMemory::new(max)))
164 }
165
166 #[must_use]
182 pub fn history_store<S>(self, store: S) -> Self
183 where
184 S: AsyncStore + WasmCompatSend + WasmCompatSync + 'static,
185 {
186 self.rebuild(|inner| inner.history = Arc::new(Persistent(store)))
187 }
188
189 #[must_use]
204 pub fn history_window(self, window: impl Recent + 'static) -> Self {
205 self.rebuild(|inner| inner.window = Arc::new(window))
206 }
207
208 #[must_use]
251 pub fn summarize_history(
252 self,
253 summarizer: Agent,
254 keep_recent: usize,
255 trigger_messages: usize,
256 ) -> Self {
257 let trigger_messages = trigger_messages.max(keep_recent.saturating_add(1));
258 self.rebuild(|inner| {
259 inner.summarizing = Some(Summarizing {
260 summarizer,
261 keep_recent,
262 trigger_messages,
263 });
264 })
265 }
266
267 #[must_use]
271 pub fn record_content(self, record: bool) -> Self {
272 self.rebuild(|inner| inner.record_content = record)
273 }
274
275 #[must_use]
281 pub fn max_concurrent_tasks(self, max: usize) -> Self {
282 self.rebuild(|inner| inner.slots = Some(Arc::new(Semaphore::new(max.max(1)))))
283 }
284
285 #[must_use]
291 pub fn max_run_duration(self, max: Duration) -> Self {
292 self.rebuild(|inner| inner.max_run = Some(max))
293 }
294
295 #[must_use]
298 pub fn max_request_bytes(self, bytes: usize) -> Self {
299 self.rebuild(|inner| inner.max_request_bytes = bytes)
300 }
301
302 pub fn track_task(&self) -> BusyGuard {
308 Busy::open(&self.inner.busy)
309 }
310
311 pub fn spawn_task<F>(&self, future: F) -> tokio::task::JoinHandle<F::Output>
324 where
325 F: Future + Send + 'static,
326 F::Output: Send + 'static,
327 {
328 let guard = self.track_task();
329 tokio::spawn(async move {
330 let _guard = guard;
331 future.await
332 })
333 }
334
335 fn rebuild(self, change: impl FnOnce(&mut Inner)) -> Self {
336 let mut inner = Arc::try_unwrap(self.inner).unwrap_or_else(|shared| (*shared).clone());
337 change(&mut inner);
338 Self {
339 inner: Arc::new(inner),
340 }
341 }
342
343 pub fn router(self) -> axum::Router {
345 let limit = self.inner.max_request_bytes;
346 axum::Router::new()
347 .route(
348 "/invocations",
349 post(invoke).layer(DefaultBodyLimit::max(limit)),
350 )
351 .route("/ping", get(ping))
352 .with_state(self)
353 }
354
355 pub async fn serve(self) -> Result<(), ServeError> {
359 let listener = listen(port_from_env(std::env::var("PORT"))).await?;
360 axum::serve(listener, self.router())
361 .with_graceful_shutdown(shutdown())
362 .await
363 .map_err(ServeError::Serve)
364 }
365}
366
367async fn shutdown() {
369 let interrupt = async {
370 let _ = tokio::signal::ctrl_c().await;
371 };
372 #[cfg(unix)]
373 let terminate = async {
374 match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
375 Ok(mut signal) => {
376 signal.recv().await;
377 }
378 Err(_) => std::future::pending::<()>().await,
379 }
380 };
381 #[cfg(not(unix))]
382 let terminate = std::future::pending::<()>();
383 tokio::select! {
384 () = interrupt => {}
385 () = terminate => {}
386 }
387}
388
389#[derive(Deserialize)]
391struct Invocation {
392 prompt: String,
393}
394
395async fn ping(State(app): State<AgentCoreApp>) -> Json<serde_json::Value> {
400 let (busy, since) = app.inner.busy.status();
401 let status = if busy { "HealthyBusy" } else { "Healthy" };
402 Json(json!({"status": status, "time_of_last_update": since}))
403}
404
405async fn invoke(
406 State(app): State<AgentCoreApp>,
407 headers: HeaderMap,
408 body: Result<Json<Invocation>, axum::extract::rejection::JsonRejection>,
409) -> Response {
410 let invocation = match body {
411 Ok(Json(invocation)) => invocation,
412 Err(rejection) => {
413 if rejection.into_response().status() == StatusCode::PAYLOAD_TOO_LARGE {
414 return error(
415 StatusCode::PAYLOAD_TOO_LARGE,
416 &format!(
417 "the request body is larger than {} bytes",
418 app.inner.max_request_bytes
419 ),
420 );
421 }
422 return error(
423 StatusCode::BAD_REQUEST,
424 "the body must be a JSON object with a \"prompt\" string",
425 );
426 }
427 };
428 let slot = match &app.inner.slots {
431 None => None,
432 Some(slots) => match Arc::clone(slots).try_acquire_owned() {
433 Ok(slot) => Some(slot),
434 Err(_) => {
435 return error(
436 StatusCode::TOO_MANY_REQUESTS,
437 "the agent is busy; try again shortly",
438 );
439 }
440 },
441 };
442 let busy = app.track_task();
445 let session = headers
446 .get(SESSION_HEADER)
447 .and_then(|value| value.to_str().ok())
448 .filter(|value| !value.is_empty())
449 .map_or_else(local_id, str::to_owned);
450 let agent_name = app.inner.agent.name().unwrap_or("agent").to_owned();
454 let span = tracing::info_span!(
455 "agentcore.invocation",
456 otel.name = %format!("invoke_agent {agent_name}"),
457 otel.kind = "server",
458 agentcore.session_id = %session,
459 gen_ai.operation.name = "invoke_agent",
460 gen_ai.agent.name = %agent_name,
461 gen_ai.task.input = tracing::field::Empty,
462 gen_ai.task.output = tracing::field::Empty,
463 agentcore.invocation.user_prompt = tracing::field::Empty,
464 agentcore.invocation.agent_response = tracing::field::Empty,
465 );
466 if app.inner.record_content {
467 span.record("gen_ai.task.input", invocation.prompt.as_str());
468 span.record(
469 "agentcore.invocation.user_prompt",
470 invocation.prompt.as_str(),
471 );
472 }
473 let _ = rig_otel::set_session(&span, session.clone(), Some(rig_otel::extract(&headers)));
475
476 let streams = headers
477 .get(header::ACCEPT)
478 .and_then(|value| value.to_str().ok())
479 .is_some_and(|accept| accept.contains("text/event-stream"));
480 if streams {
481 stream(app, session, invocation.prompt, span, slot, busy)
482 } else {
483 whole(app, session, invocation.prompt, slot, busy)
484 .instrument(span)
485 .await
486 }
487}
488
489async fn history_of(inner: &Inner, session: &str) -> Result<Vec<Message>, HistoryError> {
493 let mut messages = inner.history.load(session).await?;
494 if let Some(summarizing) = &inner.summarizing
495 && messages.len() > summarizing.trigger_messages
496 && let Some(summarized) = summarize(
497 inner.history.as_ref(),
498 summarizing,
499 session,
500 &messages,
501 inner.record_content,
502 )
503 .await
504 {
505 messages = summarized;
506 }
507 let mut sent = Vec::new();
510 let rest = match messages.split_first() {
511 Some((first, rest)) if inner.summarizing.is_some() && is_summary(first) => {
512 sent.push((**first).clone());
513 rest
514 }
515 _ => messages.as_slice(),
516 };
517 sent.extend(
518 view(rest, inner.window.as_ref())
519 .iter()
520 .map(|message| (**message).clone()),
521 );
522 Ok(sent)
523}
524
525async fn whole(
526 app: AgentCoreApp,
527 session: String,
528 prompt: String,
529 _slot: Option<OwnedSemaphorePermit>,
530 _busy: BusyGuard,
531) -> Response {
532 let inner = &app.inner;
533 let deadline = deadline_of(inner.max_run);
534 let history = match within(deadline, history_of(inner, &session)).await {
535 Ok(Ok(history)) => history,
536 Ok(Err(failure)) => {
537 tracing::warn!(error = %logged(inner.record_content, "store_error", &failure), "could not load the conversation");
538 return error(
539 StatusCode::INTERNAL_SERVER_ERROR,
540 "the conversation could not be loaded",
541 );
542 }
543 Err(_) => {
544 tracing::warn!(max = ?inner.max_run, "agent run took too long");
545 return timed_out(inner.max_run);
546 }
547 };
548 let run = within(
549 deadline,
550 inner
551 .agent
552 .prompt(prompt)
553 .history(history)
554 .record_content_telemetry(inner.record_content)
555 .run(),
556 )
557 .await;
558 match run {
559 Err(_) => {
561 tracing::warn!(max = ?inner.max_run, "agent run took too long");
562 timed_out(inner.max_run)
563 }
564 Ok(Ok(response)) => {
565 save(inner, &session, response.messages.clone()).await;
566 let answer = response.output();
567 record_answer(inner.record_content, &answer);
568 Json(json!({"response": answer, "status": "success"})).into_response()
569 }
570 Ok(Err(failure)) => {
571 tracing::warn!(error = %logged(inner.record_content, "run_failed", &failure), "agent run failed");
572 error(StatusCode::INTERNAL_SERVER_ERROR, "the agent run failed")
573 }
574 }
575}
576
577fn deadline_of(max: Option<Duration>) -> Option<tokio::time::Instant> {
579 max.map(|max| tokio::time::Instant::now() + max)
580}
581
582async fn within<F: std::future::Future>(
584 deadline: Option<tokio::time::Instant>,
585 future: F,
586) -> Result<F::Output, tokio::time::error::Elapsed> {
587 match deadline {
588 Some(deadline) => tokio::time::timeout_at(deadline, future).await,
589 None => Ok(future.await),
590 }
591}
592
593fn timeout_text(max: Option<Duration>) -> String {
594 match max {
595 Some(max) => format!("the agent run took longer than {max:?}"),
596 None => "the agent run took too long".to_owned(),
597 }
598}
599
600fn timed_out(max: Option<Duration>) -> Response {
601 error(StatusCode::GATEWAY_TIMEOUT, &timeout_text(max))
602}
603
604async fn save(inner: &Inner, session: &str, messages: Vec<Message>) {
607 let floor = inner.summarizing.as_ref().map_or(0, |summarizing| {
611 summarizing.trigger_messages.saturating_mul(2)
612 });
613 let retained = Retained {
614 window: inner.window.as_ref(),
615 floor,
616 };
617 let window: &dyn Recent = match inner.summarizing {
618 Some(_) => &retained,
619 None => inner.window.as_ref(),
620 };
621 if let Err(failure) = inner.history.append(session, messages, window).await {
622 tracing::warn!(error = %logged(inner.record_content, "store_error", &failure), "could not save the conversation");
623 }
624}
625
626fn stream(
629 app: AgentCoreApp,
630 session: String,
631 prompt: String,
632 span: tracing::Span,
633 slot: Option<OwnedSemaphorePermit>,
634 busy: BusyGuard,
635) -> Response {
636 let (sender, receiver) = mpsc::unbounded_channel::<serde_json::Value>();
637 tokio::spawn(
638 async move {
639 let _slot = slot;
640 let _busy = busy;
641 let inner = &app.inner;
642 let deadline = deadline_of(inner.max_run);
643 let history = match within(deadline, history_of(inner, &session)).await {
644 Ok(Ok(history)) => history,
645 Ok(Err(failure)) => {
646 tracing::warn!(error = %logged(inner.record_content, "store_error", &failure), "could not load the conversation");
647 let _ = sender.send(json!({"error": "the conversation could not be loaded"}));
648 return;
649 }
650 Err(_) => {
651 tracing::warn!(max = ?inner.max_run, "agent run took too long");
652 let _ = sender.send(json!({"error": timeout_text(inner.max_run)}));
653 return;
654 }
655 };
656 let mut run = inner
657 .agent
658 .prompt(prompt)
659 .history(history)
660 .record_content_telemetry(inner.record_content)
661 .stream();
662 loop {
663 let item = match within(deadline, run.next()).await {
664 Ok(Some(item)) => item,
665 Ok(None) => break,
666 Err(_) => {
667 tracing::warn!(max = ?inner.max_run, "agent run took too long");
668 let _ = sender.send(json!({"error": timeout_text(inner.max_run)}));
669 return;
670 }
671 };
672 match item {
673 Ok(MultiTurnStreamItem::StreamAssistantItem(Item::Event(
674 StreamEvent::Text { text, .. },
675 ))) => {
676 let _ = sender.send(json!({"text": text}));
677 }
678 Ok(MultiTurnStreamItem::FinalResponse(response)) => {
679 save(inner, &session, response.messages.clone()).await;
680 let answer = response.output();
681 record_answer(inner.record_content, &answer);
682 let _ = sender.send(json!({"response": answer}));
683 return;
684 }
685 Ok(_) => {}
686 Err(failure) => {
687 tracing::warn!(error = %logged(inner.record_content, "run_failed", &failure), "agent run failed");
688 let _ = sender.send(json!({"error": "the agent run failed"}));
689 return;
690 }
691 }
692 }
693 let _ = sender.send(json!({"error": "the agent run ended without an answer"}));
694 }
695 .instrument(span),
696 );
697 let events = futures::stream::unfold(receiver, |mut receiver| async move {
698 let data = receiver.recv().await?;
699 Some((
700 Ok::<_, Infallible>(Event::default().data(data.to_string())),
701 receiver,
702 ))
703 });
704 Sse::new(events).into_response()
705}
706
707pub(crate) fn logged(
710 record_content: bool,
711 kind: &'static str,
712 failure: &dyn std::fmt::Display,
713) -> String {
714 if record_content {
715 failure.to_string()
716 } else {
717 kind.to_owned()
718 }
719}
720
721fn record_answer(record_content: bool, answer: &str) {
723 if record_content {
724 let span = tracing::Span::current();
725 span.record("gen_ai.task.output", answer);
726 span.record("agentcore.invocation.agent_response", answer);
727 }
728}
729
730fn error(status: StatusCode, message: &str) -> Response {
731 (status, Json(json!({"error": message, "status": "error"}))).into_response()
732}
733
734fn port_from_env(value: Result<String, std::env::VarError>) -> u16 {
737 let value = match value {
738 Ok(value) => value,
739 Err(std::env::VarError::NotPresent) => return DEFAULT_PORT,
740 Err(std::env::VarError::NotUnicode(value)) => value.to_string_lossy().into_owned(),
741 };
742 value.parse().unwrap_or_else(|_| {
743 tracing::warn!(
744 port = %value,
745 "PORT is not a port number from 0 to 65535; serving on {DEFAULT_PORT} instead"
746 );
747 DEFAULT_PORT
748 })
749}
750
751async fn listen(port: u16) -> Result<tokio::net::TcpListener, ServeError> {
753 let address = SocketAddr::from(([0, 0, 0, 0], port));
754 tokio::net::TcpListener::bind(address)
755 .await
756 .map_err(|source| ServeError::Bind { address, source })
757}
758
759#[cfg(test)]
760mod tests {
761 use std::env::VarError;
762
763 use super::*;
764
765 #[test]
766 fn the_port_comes_from_env_or_the_default() {
767 assert_eq!(port_from_env(Ok("3200".into())), 3200);
768 assert_eq!(port_from_env(Err(VarError::NotPresent)), DEFAULT_PORT);
769 }
770
771 #[test]
772 fn a_bad_port_falls_back_to_the_default() {
773 for bad in ["", "abc", "70000", "-1", " 8080"] {
774 assert_eq!(port_from_env(Ok(bad.into())), DEFAULT_PORT, "{bad:?}");
775 }
776 }
777
778 #[tokio::test]
779 async fn a_busy_port_is_an_error_that_names_the_address() {
780 let held = listen(0).await.unwrap();
781 let port = held.local_addr().unwrap().port();
782 let message = listen(port)
783 .await
784 .err()
785 .map(|e| e.to_string())
786 .unwrap_or_default();
787 assert!(
788 message.starts_with(&format!("could not listen on 0.0.0.0:{port}: ")),
789 "{message}"
790 );
791 }
792}
793
794#[cfg(doctest)]
795#[doc = include_str!("../README.md")]
796mod readme_doctests {}