#![forbid(unsafe_code)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(
test,
allow(
clippy::expect_used,
clippy::panic,
clippy::unwrap_used,
clippy::unreachable
)
)]
mod busy;
mod history;
use std::convert::Infallible;
use std::future::Future;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use axum::Json;
use axum::extract::{DefaultBodyLimit, State};
use axum::http::{HeaderMap, StatusCode, header};
use axum::response::sse::{Event, Sse};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use futures::StreamExt;
use rig_agent::Agent;
use rig_agent::agent::MultiTurnStreamItem;
use rig_core::message::Message;
use rig_core::streaming::{Item, StreamEvent};
use rig_core::wasm_compat::{WasmCompatSend, WasmCompatSync};
use rig_memory::AsyncStore;
use rig_memory::recent::{Recent, TokenBudget, view};
use serde::Deserialize;
use serde_json::json;
use tokio::sync::mpsc;
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
use tracing::Instrument;
use crate::busy::Busy;
use crate::history::{
HistoryError, HistoryStore, InMemory, Persistent, Retained, Summarizing, is_summary, local_id,
summarize,
};
pub const SESSION_HEADER: &str = "x-amzn-bedrock-agentcore-runtime-session-id";
pub const DEFAULT_PORT: u16 = 8080;
pub const DEFAULT_MAX_SESSIONS: usize = 1000;
pub const DEFAULT_HISTORY_TOKENS: usize = 32_000;
pub const DEFAULT_MAX_REQUEST_BYTES: usize = 2 * 1024 * 1024;
pub use busy::BusyGuard;
pub use rig_memory;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ServeError {
#[error("could not listen on {address}: {source}")]
Bind {
address: SocketAddr,
#[source]
source: std::io::Error,
},
#[error("serving failed: {0}")]
Serve(#[source] std::io::Error),
}
#[derive(Clone)]
pub struct AgentCoreApp {
inner: Arc<Inner>,
}
#[derive(Clone)]
struct Inner {
agent: Agent,
history: Arc<dyn HistoryStore>,
window: Arc<dyn Recent>,
summarizing: Option<Summarizing>,
record_content: bool,
slots: Option<Arc<Semaphore>>,
max_run: Option<Duration>,
max_request_bytes: usize,
busy: Arc<Busy>,
}
impl AgentCoreApp {
pub fn new(agent: Agent) -> Self {
Self {
inner: Arc::new(Inner {
agent,
history: Arc::new(InMemory::new(DEFAULT_MAX_SESSIONS)),
window: Arc::new(TokenBudget::new(DEFAULT_HISTORY_TOKENS)),
summarizing: None,
record_content: false,
slots: None,
max_run: None,
max_request_bytes: DEFAULT_MAX_REQUEST_BYTES,
busy: Busy::new(),
}),
}
}
#[must_use]
pub fn max_sessions(self, max: usize) -> Self {
self.rebuild(|inner| inner.history = Arc::new(InMemory::new(max)))
}
#[must_use]
pub fn history_store<S>(self, store: S) -> Self
where
S: AsyncStore + WasmCompatSend + WasmCompatSync + 'static,
{
self.rebuild(|inner| inner.history = Arc::new(Persistent(store)))
}
#[must_use]
pub fn history_window(self, window: impl Recent + 'static) -> Self {
self.rebuild(|inner| inner.window = Arc::new(window))
}
#[must_use]
pub fn summarize_history(
self,
summarizer: Agent,
keep_recent: usize,
trigger_messages: usize,
) -> Self {
let trigger_messages = trigger_messages.max(keep_recent.saturating_add(1));
self.rebuild(|inner| {
inner.summarizing = Some(Summarizing {
summarizer,
keep_recent,
trigger_messages,
});
})
}
#[must_use]
pub fn record_content(self, record: bool) -> Self {
self.rebuild(|inner| inner.record_content = record)
}
#[must_use]
pub fn max_concurrent_tasks(self, max: usize) -> Self {
self.rebuild(|inner| inner.slots = Some(Arc::new(Semaphore::new(max.max(1)))))
}
#[must_use]
pub fn max_run_duration(self, max: Duration) -> Self {
self.rebuild(|inner| inner.max_run = Some(max))
}
#[must_use]
pub fn max_request_bytes(self, bytes: usize) -> Self {
self.rebuild(|inner| inner.max_request_bytes = bytes)
}
pub fn track_task(&self) -> BusyGuard {
Busy::open(&self.inner.busy)
}
pub fn spawn_task<F>(&self, future: F) -> tokio::task::JoinHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
let guard = self.track_task();
tokio::spawn(async move {
let _guard = guard;
future.await
})
}
fn rebuild(self, change: impl FnOnce(&mut Inner)) -> Self {
let mut inner = Arc::try_unwrap(self.inner).unwrap_or_else(|shared| (*shared).clone());
change(&mut inner);
Self {
inner: Arc::new(inner),
}
}
pub fn router(self) -> axum::Router {
let limit = self.inner.max_request_bytes;
axum::Router::new()
.route(
"/invocations",
post(invoke).layer(DefaultBodyLimit::max(limit)),
)
.route("/ping", get(ping))
.with_state(self)
}
pub async fn serve(self) -> Result<(), ServeError> {
let listener = listen(port_from_env(std::env::var("PORT"))).await?;
axum::serve(listener, self.router())
.with_graceful_shutdown(shutdown())
.await
.map_err(ServeError::Serve)
}
}
async fn shutdown() {
let interrupt = async {
let _ = tokio::signal::ctrl_c().await;
};
#[cfg(unix)]
let terminate = async {
match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
Ok(mut signal) => {
signal.recv().await;
}
Err(_) => std::future::pending::<()>().await,
}
};
#[cfg(not(unix))]
let terminate = std::future::pending::<()>();
tokio::select! {
() = interrupt => {}
() = terminate => {}
}
}
#[derive(Deserialize)]
struct Invocation {
prompt: String,
}
async fn ping(State(app): State<AgentCoreApp>) -> Json<serde_json::Value> {
let (busy, since) = app.inner.busy.status();
let status = if busy { "HealthyBusy" } else { "Healthy" };
Json(json!({"status": status, "time_of_last_update": since}))
}
async fn invoke(
State(app): State<AgentCoreApp>,
headers: HeaderMap,
body: Result<Json<Invocation>, axum::extract::rejection::JsonRejection>,
) -> Response {
let invocation = match body {
Ok(Json(invocation)) => invocation,
Err(rejection) => {
if rejection.into_response().status() == StatusCode::PAYLOAD_TOO_LARGE {
return error(
StatusCode::PAYLOAD_TOO_LARGE,
&format!(
"the request body is larger than {} bytes",
app.inner.max_request_bytes
),
);
}
return error(
StatusCode::BAD_REQUEST,
"the body must be a JSON object with a \"prompt\" string",
);
}
};
let slot = match &app.inner.slots {
None => None,
Some(slots) => match Arc::clone(slots).try_acquire_owned() {
Ok(slot) => Some(slot),
Err(_) => {
return error(
StatusCode::TOO_MANY_REQUESTS,
"the agent is busy; try again shortly",
);
}
},
};
let busy = app.track_task();
let session = headers
.get(SESSION_HEADER)
.and_then(|value| value.to_str().ok())
.filter(|value| !value.is_empty())
.map_or_else(local_id, str::to_owned);
let agent_name = app.inner.agent.name().unwrap_or("agent").to_owned();
let span = tracing::info_span!(
"agentcore.invocation",
otel.name = %format!("invoke_agent {agent_name}"),
otel.kind = "server",
agentcore.session_id = %session,
gen_ai.operation.name = "invoke_agent",
gen_ai.agent.name = %agent_name,
gen_ai.task.input = tracing::field::Empty,
gen_ai.task.output = tracing::field::Empty,
agentcore.invocation.user_prompt = tracing::field::Empty,
agentcore.invocation.agent_response = tracing::field::Empty,
);
if app.inner.record_content {
span.record("gen_ai.task.input", invocation.prompt.as_str());
span.record(
"agentcore.invocation.user_prompt",
invocation.prompt.as_str(),
);
}
let _ = rig_otel::set_session(&span, session.clone(), Some(rig_otel::extract(&headers)));
let streams = headers
.get(header::ACCEPT)
.and_then(|value| value.to_str().ok())
.is_some_and(|accept| accept.contains("text/event-stream"));
if streams {
stream(app, session, invocation.prompt, span, slot, busy)
} else {
whole(app, session, invocation.prompt, slot, busy)
.instrument(span)
.await
}
}
async fn history_of(inner: &Inner, session: &str) -> Result<Vec<Message>, HistoryError> {
let mut messages = inner.history.load(session).await?;
if let Some(summarizing) = &inner.summarizing
&& messages.len() > summarizing.trigger_messages
&& let Some(summarized) = summarize(
inner.history.as_ref(),
summarizing,
session,
&messages,
inner.record_content,
)
.await
{
messages = summarized;
}
let mut sent = Vec::new();
let rest = match messages.split_first() {
Some((first, rest)) if inner.summarizing.is_some() && is_summary(first) => {
sent.push((**first).clone());
rest
}
_ => messages.as_slice(),
};
sent.extend(
view(rest, inner.window.as_ref())
.iter()
.map(|message| (**message).clone()),
);
Ok(sent)
}
async fn whole(
app: AgentCoreApp,
session: String,
prompt: String,
_slot: Option<OwnedSemaphorePermit>,
_busy: BusyGuard,
) -> Response {
let inner = &app.inner;
let deadline = deadline_of(inner.max_run);
let history = match within(deadline, history_of(inner, &session)).await {
Ok(Ok(history)) => history,
Ok(Err(failure)) => {
tracing::warn!(error = %logged(inner.record_content, "store_error", &failure), "could not load the conversation");
return error(
StatusCode::INTERNAL_SERVER_ERROR,
"the conversation could not be loaded",
);
}
Err(_) => {
tracing::warn!(max = ?inner.max_run, "agent run took too long");
return timed_out(inner.max_run);
}
};
let run = within(
deadline,
inner
.agent
.prompt(prompt)
.history(history)
.record_content_telemetry(inner.record_content)
.run(),
)
.await;
match run {
Err(_) => {
tracing::warn!(max = ?inner.max_run, "agent run took too long");
timed_out(inner.max_run)
}
Ok(Ok(response)) => {
save(inner, &session, response.messages.clone()).await;
let answer = response.output();
record_answer(inner.record_content, &answer);
Json(json!({"response": answer, "status": "success"})).into_response()
}
Ok(Err(failure)) => {
tracing::warn!(error = %logged(inner.record_content, "run_failed", &failure), "agent run failed");
error(StatusCode::INTERNAL_SERVER_ERROR, "the agent run failed")
}
}
}
fn deadline_of(max: Option<Duration>) -> Option<tokio::time::Instant> {
max.map(|max| tokio::time::Instant::now() + max)
}
async fn within<F: std::future::Future>(
deadline: Option<tokio::time::Instant>,
future: F,
) -> Result<F::Output, tokio::time::error::Elapsed> {
match deadline {
Some(deadline) => tokio::time::timeout_at(deadline, future).await,
None => Ok(future.await),
}
}
fn timeout_text(max: Option<Duration>) -> String {
match max {
Some(max) => format!("the agent run took longer than {max:?}"),
None => "the agent run took too long".to_owned(),
}
}
fn timed_out(max: Option<Duration>) -> Response {
error(StatusCode::GATEWAY_TIMEOUT, &timeout_text(max))
}
async fn save(inner: &Inner, session: &str, messages: Vec<Message>) {
let floor = inner.summarizing.as_ref().map_or(0, |summarizing| {
summarizing.trigger_messages.saturating_mul(2)
});
let retained = Retained {
window: inner.window.as_ref(),
floor,
};
let window: &dyn Recent = match inner.summarizing {
Some(_) => &retained,
None => inner.window.as_ref(),
};
if let Err(failure) = inner.history.append(session, messages, window).await {
tracing::warn!(error = %logged(inner.record_content, "store_error", &failure), "could not save the conversation");
}
}
fn stream(
app: AgentCoreApp,
session: String,
prompt: String,
span: tracing::Span,
slot: Option<OwnedSemaphorePermit>,
busy: BusyGuard,
) -> Response {
let (sender, receiver) = mpsc::unbounded_channel::<serde_json::Value>();
tokio::spawn(
async move {
let _slot = slot;
let _busy = busy;
let inner = &app.inner;
let deadline = deadline_of(inner.max_run);
let history = match within(deadline, history_of(inner, &session)).await {
Ok(Ok(history)) => history,
Ok(Err(failure)) => {
tracing::warn!(error = %logged(inner.record_content, "store_error", &failure), "could not load the conversation");
let _ = sender.send(json!({"error": "the conversation could not be loaded"}));
return;
}
Err(_) => {
tracing::warn!(max = ?inner.max_run, "agent run took too long");
let _ = sender.send(json!({"error": timeout_text(inner.max_run)}));
return;
}
};
let mut run = inner
.agent
.prompt(prompt)
.history(history)
.record_content_telemetry(inner.record_content)
.stream();
loop {
let item = match within(deadline, run.next()).await {
Ok(Some(item)) => item,
Ok(None) => break,
Err(_) => {
tracing::warn!(max = ?inner.max_run, "agent run took too long");
let _ = sender.send(json!({"error": timeout_text(inner.max_run)}));
return;
}
};
match item {
Ok(MultiTurnStreamItem::StreamAssistantItem(Item::Event(
StreamEvent::Text { text, .. },
))) => {
let _ = sender.send(json!({"text": text}));
}
Ok(MultiTurnStreamItem::FinalResponse(response)) => {
save(inner, &session, response.messages.clone()).await;
let answer = response.output();
record_answer(inner.record_content, &answer);
let _ = sender.send(json!({"response": answer}));
return;
}
Ok(_) => {}
Err(failure) => {
tracing::warn!(error = %logged(inner.record_content, "run_failed", &failure), "agent run failed");
let _ = sender.send(json!({"error": "the agent run failed"}));
return;
}
}
}
let _ = sender.send(json!({"error": "the agent run ended without an answer"}));
}
.instrument(span),
);
let events = futures::stream::unfold(receiver, |mut receiver| async move {
let data = receiver.recv().await?;
Some((
Ok::<_, Infallible>(Event::default().data(data.to_string())),
receiver,
))
});
Sse::new(events).into_response()
}
pub(crate) fn logged(
record_content: bool,
kind: &'static str,
failure: &dyn std::fmt::Display,
) -> String {
if record_content {
failure.to_string()
} else {
kind.to_owned()
}
}
fn record_answer(record_content: bool, answer: &str) {
if record_content {
let span = tracing::Span::current();
span.record("gen_ai.task.output", answer);
span.record("agentcore.invocation.agent_response", answer);
}
}
fn error(status: StatusCode, message: &str) -> Response {
(status, Json(json!({"error": message, "status": "error"}))).into_response()
}
fn port_from_env(value: Result<String, std::env::VarError>) -> u16 {
let value = match value {
Ok(value) => value,
Err(std::env::VarError::NotPresent) => return DEFAULT_PORT,
Err(std::env::VarError::NotUnicode(value)) => value.to_string_lossy().into_owned(),
};
value.parse().unwrap_or_else(|_| {
tracing::warn!(
port = %value,
"PORT is not a port number from 0 to 65535; serving on {DEFAULT_PORT} instead"
);
DEFAULT_PORT
})
}
async fn listen(port: u16) -> Result<tokio::net::TcpListener, ServeError> {
let address = SocketAddr::from(([0, 0, 0, 0], port));
tokio::net::TcpListener::bind(address)
.await
.map_err(|source| ServeError::Bind { address, source })
}
#[cfg(test)]
mod tests {
use std::env::VarError;
use super::*;
#[test]
fn the_port_comes_from_env_or_the_default() {
assert_eq!(port_from_env(Ok("3200".into())), 3200);
assert_eq!(port_from_env(Err(VarError::NotPresent)), DEFAULT_PORT);
}
#[test]
fn a_bad_port_falls_back_to_the_default() {
for bad in ["", "abc", "70000", "-1", " 8080"] {
assert_eq!(port_from_env(Ok(bad.into())), DEFAULT_PORT, "{bad:?}");
}
}
#[tokio::test]
async fn a_busy_port_is_an_error_that_names_the_address() {
let held = listen(0).await.unwrap();
let port = held.local_addr().unwrap().port();
let message = listen(port)
.await
.err()
.map(|e| e.to_string())
.unwrap_or_default();
assert!(
message.starts_with(&format!("could not listen on 0.0.0.0:{port}: ")),
"{message}"
);
}
}
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
mod readme_doctests {}