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