#![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::ws::{Message as WsMessage, WebSocket, WebSocketUpgrade};
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))
.route("/ws", get(socket))
.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 streams = headers
.get(header::ACCEPT)
.and_then(|value| value.to_str().ok())
.is_some_and(|accept| accept.contains("text/event-stream"));
let session = session_header(&headers).unwrap_or_else(local_id);
let Some(run) = start_run(&app, &headers, session, invocation.prompt) else {
return error(StatusCode::TOO_MANY_REQUESTS, BUSY);
};
if streams {
stream(app, run)
} else {
let span = run.span.clone();
whole(app, run.session, run.prompt, run.slot, run.busy)
.instrument(span)
.await
}
}
const BUSY: &str = "the agent is busy; try again shortly";
fn session_header(headers: &HeaderMap) -> Option<String> {
headers
.get(SESSION_HEADER)
.and_then(|value| value.to_str().ok())
.filter(|value| !value.is_empty())
.map(str::to_owned)
}
struct Run {
session: String,
prompt: String,
span: tracing::Span,
slot: Option<OwnedSemaphorePermit>,
busy: BusyGuard,
}
fn start_run(
app: &AgentCoreApp,
headers: &HeaderMap,
session: String,
prompt: String,
) -> Option<Run> {
let slot = match &app.inner.slots {
None => None,
Some(slots) => Some(Arc::clone(slots).try_acquire_owned().ok()?),
};
let busy = app.track_task();
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", prompt.as_str());
span.record("agentcore.invocation.user_prompt", prompt.as_str());
}
let _ = rig_otel::set_session(&span, session.clone(), Some(rig_otel::extract(headers)));
Some(Run {
session,
prompt,
span,
slot,
busy,
})
}
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, run: Run) -> Response {
let body = futures::stream::unfold(events(app, run, false), |mut receiver| async move {
let data = receiver.recv().await?;
Some((
Ok::<_, Infallible>(Event::default().data(data.to_string())),
receiver,
))
});
Sse::new(body).into_response()
}
fn events(
app: AgentCoreApp,
run: Run,
cancel_on_disconnect: bool,
) -> mpsc::UnboundedReceiver<serde_json::Value> {
let Run {
session,
prompt,
span,
slot,
busy,
} = run;
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 next = if cancel_on_disconnect {
tokio::select! {
() = sender.closed() => return,
next = within(deadline, run.next()) => next,
}
} else {
within(deadline, run.next()).await
};
let item = match next {
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),
);
receiver
}
#[derive(Deserialize)]
struct WsRequest {
prompt: String,
session_id: Option<String>,
}
async fn socket(
State(app): State<AgentCoreApp>,
headers: HeaderMap,
upgrade: WebSocketUpgrade,
) -> Response {
let limit = app.inner.max_request_bytes;
let named = session_header(&headers);
upgrade
.max_message_size(limit)
.max_frame_size(limit)
.on_upgrade(move |socket| converse(app, headers, named, socket))
}
async fn converse(
app: AgentCoreApp,
headers: HeaderMap,
named: Option<String>,
mut socket: WebSocket,
) {
let limit = app.inner.max_request_bytes;
let fallback = local_id();
let mut running: Option<Running> = None;
loop {
tokio::select! {
incoming = socket.recv() => {
let text = match incoming {
Some(Ok(WsMessage::Text(text))) => text,
Some(Ok(WsMessage::Close(_))) | None => break,
Some(Ok(WsMessage::Ping(_) | WsMessage::Pong(_))) => continue,
Some(Ok(WsMessage::Binary(_))) => {
if !send(&mut socket, error_frame(BINARY)).await {
break;
}
continue;
}
Some(Err(_)) => {
let frame = error_frame(&format!(
"the message could not be read; a message is limited to {limit} bytes"
));
let _ = send(&mut socket, frame).await;
break;
}
};
if running.is_some() {
if !send(&mut socket, error_frame(BUSY)).await {
break;
}
continue;
}
let request = match serde_json::from_str::<WsRequest>(text.as_str()) {
Ok(request) => request,
Err(_) => {
if !send(&mut socket, error_frame(BAD_MESSAGE)).await {
break;
}
continue;
}
};
let session = named
.clone()
.or_else(|| request.session_id.filter(|id| !id.is_empty()))
.unwrap_or_else(|| fallback.clone());
match start_run(&app, &headers, session.clone(), request.prompt) {
Some(run) => {
running = Some(Running {
session,
events: events(app.clone(), run, true),
stashed: None,
});
}
None => {
if !send(&mut socket, error_frame(BUSY)).await {
break;
}
}
}
}
next = next_event(&mut running), if running.is_some() => match next {
Some(frame) => {
if !send(&mut socket, frame).await {
break;
}
}
None => running = None,
},
}
}
}
struct Running {
session: String,
events: mpsc::UnboundedReceiver<serde_json::Value>,
stashed: Option<serde_json::Value>,
}
const BINARY: &str = "binary messages are not supported; send a text message holding a JSON object";
const BAD_MESSAGE: &str = "the message must be a JSON object with a \"prompt\" string";
async fn send(socket: &mut WebSocket, frame: serde_json::Value) -> bool {
socket
.send(WsMessage::Text(frame.to_string().into()))
.await
.is_ok()
}
const TEXT_WINDOW: Duration = Duration::from_millis(10);
const TEXT_FRAME_BYTES: usize = 16 * 1024;
const MAX_FRAME_BYTES: usize = 64 * 1024;
async fn next_event(running: &mut Option<Running>) -> Option<serde_json::Value> {
let Some(running) = running else {
return std::future::pending().await;
};
let event = match running.stashed.take() {
Some(event) => event,
None => running.events.recv().await?,
};
let Some(mut text) = text_of(&event).map(str::to_owned) else {
return Some(frame(&event, &running.session));
};
let window = tokio::time::sleep(TEXT_WINDOW);
tokio::pin!(window);
while text.len() < TEXT_FRAME_BYTES {
tokio::select! {
() = &mut window => break,
next = running.events.recv() => match next {
None => break,
Some(next) => match text_of(&next) {
Some(more) => text.push_str(more),
None => {
running.stashed = Some(next);
break;
}
},
},
}
}
Some(frame(&json!({"text": text}), &running.session))
}
fn text_of(event: &serde_json::Value) -> Option<&str> {
event.get("text").and_then(serde_json::Value::as_str)
}
fn frame(event: &serde_json::Value, session: &str) -> serde_json::Value {
let kind = if event.get("error").is_some() {
"error"
} else if event.get("response").is_some() {
"agent_response"
} else {
"agent_text"
};
let mut frame = event.clone();
if let Some(object) = frame.as_object_mut() {
object.insert("session_id".to_owned(), json!(session));
object.insert("message_type".to_owned(), json!(kind));
}
if frame.to_string().len() > MAX_FRAME_BYTES {
return error_frame(
"the reply is larger than the 64 KB WebSocket frame limit; its text was streamed in agent_text frames, or use /invocations",
);
}
frame
}
fn error_frame(message: &str) -> serde_json::Value {
json!({"error": message, "status": "error", "message_type": "error"})
}
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 {}