1#![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
63pub const SESSION_HEADER: &str = "x-amzn-bedrock-agentcore-runtime-session-id";
65
66pub const DEFAULT_PORT: u16 = 8080;
68
69pub const DEFAULT_MAX_SESSIONS: usize = 1000;
73
74pub const DEFAULT_HISTORY_TOKENS: usize = 32_000;
76
77pub use rig_memory;
79
80#[derive(Debug, thiserror::Error)]
82#[non_exhaustive]
83pub enum ServeError {
84 #[error("could not listen on {address}: {source}")]
86 Bind {
87 address: SocketAddr,
89 #[source]
91 source: std::io::Error,
92 },
93 #[error("serving failed: {0}")]
95 Serve(#[source] std::io::Error),
96}
97
98#[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 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 #[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 #[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 #[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 #[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 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 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
214async 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#[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 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 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
301async 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
344async 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
356fn 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
413fn 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}