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