bedrock-agentcore 0.1.0

Amazon Bedrock AgentCore SDK for Rust
Documentation
//! An agent that starts work in the background and replies at once.
//!
//! `{"prompt": ..}` starts a Strands agent in a background task. While the task runs,
//! `GET /ping` reports `HealthyBusy`, so AgentCore Runtime keeps the session even
//! though no invocation is in progress. `{}` on the same session returns the report,
//! or `null` while the agent still works.
//!
//! Run it with `cargo run --example background`, then:
//!
//! ```text
//! curl -s localhost:8080/invocations \
//!   -H 'X-Amzn-Bedrock-AgentCore-Runtime-Session-Id: local-session' \
//!   -d '{"prompt": "The history of the Rust programming language"}'
//! curl -s localhost:8080/ping
//! curl -s localhost:8080/invocations \
//!   -H 'X-Amzn-Bedrock-AgentCore-Runtime-Session-Id: local-session' \
//!   -d '{}'
//! ```

use std::sync::Mutex;

use bedrock_agentcore::{RequestContext, context, runtime::BedrockAgentCoreApp};
use serde::Deserialize;
use serde_json::{Value, json};
use strands::{Agent, models::bedrock::BedrockModel};
use tracing::Instrument;

#[derive(Deserialize)]
struct Request {
    prompt: Option<String>,
}

/// AgentCore Runtime gives each session its own microVM, so one slot is enough.
static REPORT: Mutex<Option<String>> = Mutex::new(None);

async fn research(model: BedrockModel, prompt: String) -> strands::Result<String> {
    let mut agent = Agent::builder()
        .model(model)
        .system_prompt("You write a report of about 600 words on the user's topic.")
        .printer(false)
        .build()?;
    let result = agent.invoke(prompt).await?;
    agent.shutdown().await?;
    Ok(result.to_string())
}

#[tokio::main]
async fn main() -> Result<(), bedrock_agentcore::Error> {
    tracing_subscriber::fmt().with_ansi(false).init();
    let model = BedrockModel::builder().model_id("global.anthropic.claude-sonnet-4-6").max_tokens(4096).build();

    let handle = move |request: Request, ctx: RequestContext| {
        let model = model.clone();
        async move {
            let Some(prompt) = request.prompt else {
                let report = REPORT.lock().map(|report| report.clone()).unwrap_or_default();
                return Ok(json!({ "report": report, "active_tasks": ctx.tasks().active_count() }));
            };

            // `tracked` registers the task here and ties it to the work. The task stays
            // tracked until the work ends, however it ends.
            let work = ctx.tasks().tracked("research", async move {
                let report = research(model, prompt).await.unwrap_or_else(|error| format!("failed: {error}"));
                tracing::info!(characters = report.len(), "background work finished");
                if let Ok(mut slot) = REPORT.lock() {
                    *slot = Some(report);
                }
            });
            // `context::scope` carries the request context. The tracing span is separate:
            // `in_current_span` keeps the request ID and session ID on the task's log lines.
            tokio::spawn(context::scope(ctx.clone(), work).in_current_span());
            Ok::<Value, std::convert::Infallible>(json!({ "active_tasks": ctx.tasks().active_count() }))
        }
    };
    BedrockAgentCoreApp::builder().invocation(handle).build()?.run().await
}