Skip to main content

rig_agentcore/
lib.rs

1//! Run a [Rig](https://github.com/0xPlaygrounds/rig) agent on AWS Bedrock
2//! AgentCore Runtime.
3//!
4//! AgentCore runs an agent as an ARM64 container that serves its HTTP
5//! protocol contract on port 8080: `POST /invocations` with a JSON body,
6//! answered with JSON or server-sent events, and `GET /ping`. Each runtime
7//! session (the `X-Amzn-Bedrock-AgentCore-Runtime-Session-Id` header) is one
8//! conversation. [`AgentCoreApp`] serves that contract for a Rig agent:
9//!
10//! - the session's conversation is kept between invocations, in memory or in
11//!   any [`rig_memory`] store (see [`AgentCoreApp::history_store`]);
12//! - the reply streams as server-sent events when the caller asks for
13//!   `text/event-stream`, and is one JSON object otherwise;
14//! - each invocation runs in a span that continues the caller's trace and
15//!   carries the session as `session.id` (through [`rig_otel`]), which is what
16//!   AgentCore Observability and Evaluations group a session's traces by.
17//!
18//! ```no_run
19//! # async fn run(agent: rig_agent::Agent) -> Result<(), rig_agentcore::ServeError> {
20//! rig_agentcore::AgentCoreApp::new(agent).serve().await
21//! # }
22//! ```
23
24#![forbid(unsafe_code)]
25#![cfg_attr(docsrs, feature(doc_cfg))]
26#![cfg_attr(
27    test,
28    allow(
29        clippy::expect_used,
30        clippy::panic,
31        clippy::unwrap_used,
32        clippy::unreachable
33    )
34)]
35
36mod history;
37
38use std::convert::Infallible;
39use std::net::SocketAddr;
40use std::sync::Arc;
41
42use axum::Json;
43use axum::extract::State;
44use axum::http::{HeaderMap, StatusCode, header};
45use axum::response::sse::{Event, Sse};
46use axum::response::{IntoResponse, Response};
47use axum::routing::{get, post};
48use futures::StreamExt;
49use rig_agent::Agent;
50use rig_agent::agent::MultiTurnStreamItem;
51use rig_core::message::Message;
52use rig_core::streaming::{Item, StreamEvent};
53use rig_core::wasm_compat::{WasmCompatSend, WasmCompatSync};
54use rig_memory::AsyncStore;
55use rig_memory::recent::{Recent, TokenBudget, view};
56use serde::Deserialize;
57use serde_json::json;
58use tokio::sync::mpsc;
59use tracing::Instrument;
60
61use crate::history::{HistoryError, HistoryStore, InMemory, Persistent, local_id};
62
63/// The header AgentCore Runtime names the session with.
64pub const SESSION_HEADER: &str = "x-amzn-bedrock-agentcore-runtime-session-id";
65
66/// The port AgentCore Runtime sends the HTTP protocol to.
67pub const DEFAULT_PORT: u16 = 8080;
68
69/// How many sessions an app keeps by default. AgentCore gives each session
70/// its own microVM, so one process usually sees one; this bounds the memory
71/// when the app runs elsewhere.
72pub const DEFAULT_MAX_SESSIONS: usize = 1000;
73
74/// How many tokens of history a session keeps by default.
75pub const DEFAULT_HISTORY_TOKENS: usize = 32_000;
76
77/// The session stores and history windows conversations are kept with.
78pub use rig_memory;
79
80/// Why the app stopped serving.
81#[derive(Debug, thiserror::Error)]
82#[non_exhaustive]
83pub enum ServeError {
84    /// The port could not be bound.
85    #[error("could not listen on {address}: {source}")]
86    Bind {
87        /// The address.
88        address: SocketAddr,
89        /// The error.
90        #[source]
91        source: std::io::Error,
92    },
93    /// Serving failed.
94    #[error("serving failed: {0}")]
95    Serve(#[source] std::io::Error),
96}
97
98/// A Rig agent served on AgentCore Runtime's HTTP protocol contract.
99#[derive(Clone)]
100pub struct AgentCoreApp {
101    inner: Arc<Inner>,
102}
103
104#[derive(Clone)]
105struct Inner {
106    agent: Agent,
107    history: Arc<dyn HistoryStore>,
108    window: Arc<dyn Recent>,
109    record_content: bool,
110}
111
112impl AgentCoreApp {
113    /// Serve `agent`.
114    pub fn new(agent: Agent) -> Self {
115        Self {
116            inner: Arc::new(Inner {
117                agent,
118                history: Arc::new(InMemory::new(DEFAULT_MAX_SESSIONS)),
119                window: Arc::new(TokenBudget::new(DEFAULT_HISTORY_TOKENS)),
120                record_content: false,
121            }),
122        }
123    }
124
125    /// Keep at most `max` sessions' conversations in memory, forgetting the
126    /// oldest. This is the default, with [`DEFAULT_MAX_SESSIONS`]. It replaces
127    /// a store set with [`history_store`](Self::history_store).
128    #[must_use]
129    pub fn max_sessions(self, max: usize) -> Self {
130        self.rebuild(|inner| inner.history = Arc::new(InMemory::new(max)))
131    }
132
133    /// Keep sessions in `store`, one session log per session id, so they
134    /// survive restarts and several apps can share them: any [`rig_memory`]
135    /// store, such as `rig_memory::DirStore` (feature `fs`) or the
136    /// `rig-sqlite` and `rig-postgres` stores. Any session id works: one that
137    /// is 1 to 128 ASCII letters, digits, `-` or `_` names its log as it is,
138    /// any other is hashed into a safe log name. Two apps, or concurrent
139    /// invocations of one session, saving at once do not lose either turn: a
140    /// save that loses a race rereads and retries up to 10 times with a short
141    /// jittered backoff. If a save still fails, the invocation's answer is
142    /// returned anyway, the failure is logged, and that run's turn is not
143    /// persisted, so later invocations do not see it. A load that fails is
144    /// reported to the caller as an error, before the agent runs. The store
145    /// keeps each session's whole conversation;
146    /// [`history_window`](Self::history_window) limits only what an invocation
147    /// sends. Replaces the in-memory store set by [`max_sessions`](Self::max_sessions).
148    #[must_use]
149    pub fn history_store<S>(self, store: S) -> Self
150    where
151        S: AsyncStore + WasmCompatSend + WasmCompatSync + 'static,
152    {
153        self.rebuild(|inner| inner.history = Arc::new(Persistent(store)))
154    }
155
156    /// Which newest messages of a session each invocation sends the model,
157    /// such as `rig_memory::recent::TokenBudget::new(8_000)` or
158    /// `LastMessages(20)`. Defaults to [`DEFAULT_HISTORY_TOKENS`] tokens. A
159    /// tool result is never sent without its call. An empty window
160    /// (`TokenBudget::new(0)`, `LastMessages(0)`) sends no history.
161    ///
162    /// What the window also does depends on the store. In memory, messages
163    /// beyond it are forgotten when a run is saved, so memory stays bounded.
164    /// With [`history_store`](Self::history_store), the store keeps the whole
165    /// conversation and the window only limits what is sent, so a later,
166    /// wider window sees older turns again.
167    #[must_use]
168    pub fn history_window(self, window: impl Recent + 'static) -> Self {
169        self.rebuild(|inner| inner.window = Arc::new(window))
170    }
171
172    /// Record prompts and replies on the GenAI spans. AgentCore Evaluations
173    /// needs them to judge a session; they are off by default, as in Rig,
174    /// because they put conversation content into your telemetry.
175    #[must_use]
176    pub fn record_content(self, record: bool) -> Self {
177        self.rebuild(|inner| inner.record_content = record)
178    }
179
180    fn rebuild(self, change: impl FnOnce(&mut Inner)) -> Self {
181        let mut inner = Arc::try_unwrap(self.inner).unwrap_or_else(|shared| (*shared).clone());
182        change(&mut inner);
183        Self {
184            inner: Arc::new(inner),
185        }
186    }
187
188    /// The contract's routes, `/invocations` and `/ping`, as an Axum router.
189    pub fn router(self) -> axum::Router {
190        axum::Router::new()
191            .route("/invocations", post(invoke))
192            .route("/ping", get(ping))
193            .with_state(self)
194    }
195
196    /// Serve on `0.0.0.0` at `PORT` (default 8080, what AgentCore sends to)
197    /// until the process gets Ctrl-C or SIGTERM.
198    pub async fn serve(self) -> Result<(), ServeError> {
199        let port = std::env::var("PORT")
200            .ok()
201            .and_then(|port| port.parse().ok())
202            .unwrap_or(DEFAULT_PORT);
203        let address = SocketAddr::from(([0, 0, 0, 0], port));
204        let listener = tokio::net::TcpListener::bind(address)
205            .await
206            .map_err(|source| ServeError::Bind { address, source })?;
207        axum::serve(listener, self.router())
208            .with_graceful_shutdown(shutdown())
209            .await
210            .map_err(ServeError::Serve)
211    }
212}
213
214/// Resolves when the process is asked to stop.
215async fn shutdown() {
216    let interrupt = async {
217        let _ = tokio::signal::ctrl_c().await;
218    };
219    #[cfg(unix)]
220    let terminate = async {
221        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
222            Ok(mut signal) => {
223                signal.recv().await;
224            }
225            Err(_) => std::future::pending::<()>().await,
226        }
227    };
228    #[cfg(not(unix))]
229    let terminate = std::future::pending::<()>();
230    tokio::select! {
231        () = interrupt => {}
232        () = terminate => {}
233    }
234}
235
236/// The `/invocations` body: AgentCore passes the caller's payload as is.
237#[derive(Deserialize)]
238struct Invocation {
239    prompt: String,
240}
241
242async fn ping() -> Json<serde_json::Value> {
243    Json(json!({"status": "Healthy"}))
244}
245
246async fn invoke(
247    State(app): State<AgentCoreApp>,
248    headers: HeaderMap,
249    body: Result<Json<Invocation>, axum::extract::rejection::JsonRejection>,
250) -> Response {
251    let Ok(Json(invocation)) = body else {
252        return error(
253            StatusCode::BAD_REQUEST,
254            "the body must be a JSON object with a \"prompt\" string",
255        );
256    };
257    let session = headers
258        .get(SESSION_HEADER)
259        .and_then(|value| value.to_str().ok())
260        .filter(|value| !value.is_empty())
261        .map_or_else(local_id, str::to_owned);
262    // The invocation is the agent run AgentCore Evaluations looks for: an
263    // `invoke_agent` span (Rig adopts it as the run's span, so it makes none
264    // of its own), with the prompt and the answer when content is recorded.
265    let agent_name = app.inner.agent.name().unwrap_or("agent").to_owned();
266    let span = tracing::info_span!(
267        "agentcore.invocation",
268        otel.name = %format!("invoke_agent {agent_name}"),
269        otel.kind = "server",
270        agentcore.session_id = %session,
271        gen_ai.operation.name = "invoke_agent",
272        gen_ai.agent.name = %agent_name,
273        gen_ai.task.input = tracing::field::Empty,
274        gen_ai.task.output = tracing::field::Empty,
275        agentcore.invocation.user_prompt = tracing::field::Empty,
276        agentcore.invocation.agent_response = tracing::field::Empty,
277    );
278    if app.inner.record_content {
279        span.record("gen_ai.task.input", invocation.prompt.as_str());
280        span.record(
281            "agentcore.invocation.user_prompt",
282            invocation.prompt.as_str(),
283        );
284    }
285    // Without an OpenTelemetry layer there is nothing to continue: fine.
286    let _ = rig_otel::set_session(&span, session.clone(), Some(rig_otel::extract(&headers)));
287
288    let streams = headers
289        .get(header::ACCEPT)
290        .and_then(|value| value.to_str().ok())
291        .is_some_and(|accept| accept.contains("text/event-stream"));
292    if streams {
293        stream(app, session, invocation.prompt, span)
294    } else {
295        whole(app, session, invocation.prompt)
296            .instrument(span)
297            .await
298    }
299}
300
301/// The session's conversation as a request sends it: the newest messages
302/// the window keeps.
303async fn history_of(inner: &Inner, session: &str) -> Result<Vec<Message>, HistoryError> {
304    let messages = inner.history.load(session).await?;
305    Ok(view(&messages, inner.window.as_ref())
306        .iter()
307        .map(|message| (**message).clone())
308        .collect())
309}
310
311async fn whole(app: AgentCoreApp, session: String, prompt: String) -> Response {
312    let inner = &app.inner;
313    let history = match history_of(inner, &session).await {
314        Ok(history) => history,
315        Err(failure) => {
316            tracing::warn!(error = %failure, "could not load the conversation");
317            return error(
318                StatusCode::INTERNAL_SERVER_ERROR,
319                "the conversation could not be loaded",
320            );
321        }
322    };
323    let run = inner
324        .agent
325        .prompt(prompt)
326        .history(history)
327        .record_content_telemetry(inner.record_content)
328        .run()
329        .await;
330    match run {
331        Ok(response) => {
332            save(inner, &session, response.messages.clone()).await;
333            let answer = response.output();
334            record_answer(inner.record_content, &answer);
335            Json(json!({"response": answer, "status": "success"})).into_response()
336        }
337        Err(failure) => {
338            tracing::warn!(error = %failure, "agent run failed");
339            error(StatusCode::INTERNAL_SERVER_ERROR, "the agent run failed")
340        }
341    }
342}
343
344/// Add a finished run to its session. A save that fails is logged, not
345/// reported: the answer was already produced.
346async fn save(inner: &Inner, session: &str, messages: Vec<Message>) {
347    if let Err(failure) = inner
348        .history
349        .append(session, messages, inner.window.as_ref())
350        .await
351    {
352        tracing::warn!(error = %failure, "could not save the conversation");
353    }
354}
355
356/// Stream the reply as server-sent events: `{"text": ...}` as the model
357/// writes, then `{"response": ...}` with the whole answer, or `{"error": ...}`.
358fn stream(app: AgentCoreApp, session: String, prompt: String, span: tracing::Span) -> Response {
359    let (sender, receiver) = mpsc::unbounded_channel::<serde_json::Value>();
360    tokio::spawn(
361        async move {
362            let inner = &app.inner;
363            let history = match history_of(inner, &session).await {
364                Ok(history) => history,
365                Err(failure) => {
366                    tracing::warn!(error = %failure, "could not load the conversation");
367                    let _ = sender.send(json!({"error": "the conversation could not be loaded"}));
368                    return;
369                }
370            };
371            let mut run = inner
372                .agent
373                .prompt(prompt)
374                .history(history)
375                .record_content_telemetry(inner.record_content)
376                .stream();
377            while let Some(item) = run.next().await {
378                match item {
379                    Ok(MultiTurnStreamItem::StreamAssistantItem(Item::Event(
380                        StreamEvent::Text { text, .. },
381                    ))) => {
382                        let _ = sender.send(json!({"text": text}));
383                    }
384                    Ok(MultiTurnStreamItem::FinalResponse(response)) => {
385                        save(inner, &session, response.messages.clone()).await;
386                        let answer = response.output();
387                        record_answer(inner.record_content, &answer);
388                        let _ = sender.send(json!({"response": answer}));
389                        return;
390                    }
391                    Ok(_) => {}
392                    Err(failure) => {
393                        tracing::warn!(error = %failure, "agent run failed");
394                        let _ = sender.send(json!({"error": "the agent run failed"}));
395                        return;
396                    }
397                }
398            }
399            let _ = sender.send(json!({"error": "the agent run ended without an answer"}));
400        }
401        .instrument(span),
402    );
403    let events = futures::stream::unfold(receiver, |mut receiver| async move {
404        let data = receiver.recv().await?;
405        Some((
406            Ok::<_, Infallible>(Event::default().data(data.to_string())),
407            receiver,
408        ))
409    });
410    Sse::new(events).into_response()
411}
412
413/// Record the agent's answer on the invocation span, the current one.
414fn record_answer(record_content: bool, answer: &str) {
415    if record_content {
416        let span = tracing::Span::current();
417        span.record("gen_ai.task.output", answer);
418        span.record("agentcore.invocation.agent_response", answer);
419    }
420}
421
422fn error(status: StatusCode, message: &str) -> Response {
423    (status, Json(json!({"error": message, "status": "error"}))).into_response()
424}