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;
11//! - the reply streams as server-sent events when the caller asks for
12//!   `text/event-stream`, and is one JSON object otherwise;
13//! - each invocation runs in a span that continues the caller's trace and
14//!   carries the session as `session.id` (through [`rig_otel`]), which is what
15//!   AgentCore Observability and Evaluations group a session's traces by.
16//!
17//! ```no_run
18//! # async fn run(agent: rig_agent::Agent) -> Result<(), rig_agentcore::ServeError> {
19//! rig_agentcore::AgentCoreApp::new(agent).serve().await
20//! # }
21//! ```
22
23#![forbid(unsafe_code)]
24#![cfg_attr(docsrs, feature(doc_cfg))]
25#![cfg_attr(
26    test,
27    allow(
28        clippy::expect_used,
29        clippy::panic,
30        clippy::unwrap_used,
31        clippy::unreachable
32    )
33)]
34
35mod sessions;
36
37use std::convert::Infallible;
38use std::net::SocketAddr;
39use std::sync::Arc;
40
41use axum::Json;
42use axum::extract::State;
43use axum::http::{HeaderMap, StatusCode, header};
44use axum::response::sse::{Event, Sse};
45use axum::response::{IntoResponse, Response};
46use axum::routing::{get, post};
47use futures::StreamExt;
48use rig_agent::Agent;
49use rig_agent::agent::MultiTurnStreamItem;
50use rig_core::streaming::{Item, StreamEvent};
51use serde::Deserialize;
52use serde_json::json;
53use tokio::sync::mpsc;
54use tracing::Instrument;
55
56use crate::sessions::Sessions;
57
58/// The header AgentCore Runtime names the session with.
59pub const SESSION_HEADER: &str = "x-amzn-bedrock-agentcore-runtime-session-id";
60
61/// The port AgentCore Runtime sends the HTTP protocol to.
62pub const DEFAULT_PORT: u16 = 8080;
63
64/// How many sessions an app keeps by default. AgentCore gives each session
65/// its own microVM, so one process usually sees one; this bounds the memory
66/// when the app runs elsewhere.
67pub const DEFAULT_MAX_SESSIONS: usize = 1000;
68
69/// Why the app stopped serving.
70#[derive(Debug, thiserror::Error)]
71#[non_exhaustive]
72pub enum ServeError {
73    /// The port could not be bound.
74    #[error("could not listen on {address}: {source}")]
75    Bind {
76        /// The address.
77        address: SocketAddr,
78        /// The error.
79        #[source]
80        source: std::io::Error,
81    },
82    /// Serving failed.
83    #[error("serving failed: {0}")]
84    Serve(#[source] std::io::Error),
85}
86
87/// A Rig agent served on AgentCore Runtime's HTTP protocol contract.
88#[derive(Clone)]
89pub struct AgentCoreApp {
90    inner: Arc<Inner>,
91}
92
93struct Inner {
94    agent: Agent,
95    sessions: Sessions,
96    record_content: bool,
97}
98
99impl AgentCoreApp {
100    /// Serve `agent`.
101    pub fn new(agent: Agent) -> Self {
102        Self {
103            inner: Arc::new(Inner {
104                agent,
105                sessions: Sessions::new(DEFAULT_MAX_SESSIONS),
106                record_content: false,
107            }),
108        }
109    }
110
111    /// Keep at most `max` sessions' conversations, forgetting the oldest.
112    #[must_use]
113    pub fn max_sessions(self, max: usize) -> Self {
114        self.rebuild(|inner| inner.sessions = Sessions::new(max))
115    }
116
117    /// Record prompts and replies on the GenAI spans. AgentCore Evaluations
118    /// needs them to judge a session; they are off by default, as in Rig,
119    /// because they put conversation content into your telemetry.
120    #[must_use]
121    pub fn record_content(self, record: bool) -> Self {
122        self.rebuild(|inner| inner.record_content = record)
123    }
124
125    fn rebuild(self, change: impl FnOnce(&mut Inner)) -> Self {
126        let mut inner = match Arc::try_unwrap(self.inner) {
127            Ok(inner) => inner,
128            Err(shared) => Inner {
129                agent: shared.agent.clone(),
130                sessions: Sessions::new(shared.sessions.capacity()),
131                record_content: shared.record_content,
132            },
133        };
134        change(&mut inner);
135        Self {
136            inner: Arc::new(inner),
137        }
138    }
139
140    /// The contract's routes, `/invocations` and `/ping`, as an Axum router.
141    pub fn router(self) -> axum::Router {
142        axum::Router::new()
143            .route("/invocations", post(invoke))
144            .route("/ping", get(ping))
145            .with_state(self)
146    }
147
148    /// Serve on `0.0.0.0` at `PORT` (default 8080, what AgentCore sends to)
149    /// until the process gets Ctrl-C or SIGTERM.
150    pub async fn serve(self) -> Result<(), ServeError> {
151        let port = std::env::var("PORT")
152            .ok()
153            .and_then(|port| port.parse().ok())
154            .unwrap_or(DEFAULT_PORT);
155        let address = SocketAddr::from(([0, 0, 0, 0], port));
156        let listener = tokio::net::TcpListener::bind(address)
157            .await
158            .map_err(|source| ServeError::Bind { address, source })?;
159        axum::serve(listener, self.router())
160            .with_graceful_shutdown(shutdown())
161            .await
162            .map_err(ServeError::Serve)
163    }
164}
165
166/// Resolves when the process is asked to stop.
167async fn shutdown() {
168    let interrupt = async {
169        let _ = tokio::signal::ctrl_c().await;
170    };
171    #[cfg(unix)]
172    let terminate = async {
173        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
174            Ok(mut signal) => {
175                signal.recv().await;
176            }
177            Err(_) => std::future::pending::<()>().await,
178        }
179    };
180    #[cfg(not(unix))]
181    let terminate = std::future::pending::<()>();
182    tokio::select! {
183        () = interrupt => {}
184        () = terminate => {}
185    }
186}
187
188/// The `/invocations` body: AgentCore passes the caller's payload as is.
189#[derive(Deserialize)]
190struct Invocation {
191    prompt: String,
192}
193
194async fn ping() -> Json<serde_json::Value> {
195    Json(json!({"status": "Healthy"}))
196}
197
198async fn invoke(
199    State(app): State<AgentCoreApp>,
200    headers: HeaderMap,
201    body: Result<Json<Invocation>, axum::extract::rejection::JsonRejection>,
202) -> Response {
203    let Ok(Json(invocation)) = body else {
204        return error(
205            StatusCode::BAD_REQUEST,
206            "the body must be a JSON object with a \"prompt\" string",
207        );
208    };
209    let session = headers
210        .get(SESSION_HEADER)
211        .and_then(|value| value.to_str().ok())
212        .filter(|value| !value.is_empty())
213        .map_or_else(sessions::local_id, str::to_owned);
214    // The invocation is the agent run AgentCore Evaluations looks for: an
215    // `invoke_agent` span (Rig adopts it as the run's span, so it makes none
216    // of its own), with the prompt and the answer when content is recorded.
217    let agent_name = app.inner.agent.name().unwrap_or("agent").to_owned();
218    let span = tracing::info_span!(
219        "agentcore.invocation",
220        otel.name = %format!("invoke_agent {agent_name}"),
221        otel.kind = "server",
222        agentcore.session_id = %session,
223        gen_ai.operation.name = "invoke_agent",
224        gen_ai.agent.name = %agent_name,
225        gen_ai.task.input = tracing::field::Empty,
226        gen_ai.task.output = tracing::field::Empty,
227        agentcore.invocation.user_prompt = tracing::field::Empty,
228        agentcore.invocation.agent_response = tracing::field::Empty,
229    );
230    if app.inner.record_content {
231        span.record("gen_ai.task.input", invocation.prompt.as_str());
232        span.record(
233            "agentcore.invocation.user_prompt",
234            invocation.prompt.as_str(),
235        );
236    }
237    // Without an OpenTelemetry layer there is nothing to continue: fine.
238    let _ = rig_otel::set_session(&span, session.clone(), Some(rig_otel::extract(&headers)));
239
240    let streams = headers
241        .get(header::ACCEPT)
242        .and_then(|value| value.to_str().ok())
243        .is_some_and(|accept| accept.contains("text/event-stream"));
244    if streams {
245        stream(app, session, invocation.prompt, span)
246    } else {
247        whole(app, session, invocation.prompt)
248            .instrument(span)
249            .await
250    }
251}
252
253async fn whole(app: AgentCoreApp, session: String, prompt: String) -> Response {
254    let inner = &app.inner;
255    let history = inner.sessions.history(&session);
256    let run = inner
257        .agent
258        .prompt(prompt)
259        .history(history)
260        .record_content_telemetry(inner.record_content)
261        .run()
262        .await;
263    match run {
264        Ok(response) => {
265            inner.sessions.append(&session, response.messages.clone());
266            let answer = response.output();
267            record_answer(inner.record_content, &answer);
268            Json(json!({"response": answer, "status": "success"})).into_response()
269        }
270        Err(failure) => {
271            tracing::warn!(error = %failure, "agent run failed");
272            error(StatusCode::INTERNAL_SERVER_ERROR, "the agent run failed")
273        }
274    }
275}
276
277/// Stream the reply as server-sent events: `{"text": ...}` as the model
278/// writes, then `{"response": ...}` with the whole answer, or `{"error": ...}`.
279fn stream(app: AgentCoreApp, session: String, prompt: String, span: tracing::Span) -> Response {
280    let (sender, receiver) = mpsc::unbounded_channel::<serde_json::Value>();
281    tokio::spawn(
282        async move {
283            let inner = &app.inner;
284            let history = inner.sessions.history(&session);
285            let mut run = inner
286                .agent
287                .prompt(prompt)
288                .history(history)
289                .record_content_telemetry(inner.record_content)
290                .stream();
291            while let Some(item) = run.next().await {
292                match item {
293                    Ok(MultiTurnStreamItem::StreamAssistantItem(Item::Event(
294                        StreamEvent::Text { text, .. },
295                    ))) => {
296                        let _ = sender.send(json!({"text": text}));
297                    }
298                    Ok(MultiTurnStreamItem::FinalResponse(response)) => {
299                        inner.sessions.append(&session, response.messages.clone());
300                        let answer = response.output();
301                        record_answer(inner.record_content, &answer);
302                        let _ = sender.send(json!({"response": answer}));
303                        return;
304                    }
305                    Ok(_) => {}
306                    Err(failure) => {
307                        tracing::warn!(error = %failure, "agent run failed");
308                        let _ = sender.send(json!({"error": "the agent run failed"}));
309                        return;
310                    }
311                }
312            }
313            let _ = sender.send(json!({"error": "the agent run ended without an answer"}));
314        }
315        .instrument(span),
316    );
317    let events = futures::stream::unfold(receiver, |mut receiver| async move {
318        let data = receiver.recv().await?;
319        Some((
320            Ok::<_, Infallible>(Event::default().data(data.to_string())),
321            receiver,
322        ))
323    });
324    Sse::new(events).into_response()
325}
326
327/// Record the agent's answer on the invocation span, the current one.
328fn record_answer(record_content: bool, answer: &str) {
329    if record_content {
330        let span = tracing::Span::current();
331        span.record("gen_ai.task.output", answer);
332        span.record("agentcore.invocation.agent_response", answer);
333    }
334}
335
336fn error(status: StatusCode, message: &str) -> Response {
337    (status, Json(json!({"error": message, "status": "error"}))).into_response()
338}