bedrock-agentcore 0.1.0

Amazon Bedrock AgentCore SDK for Rust
Documentation
//! An agent that streams its reply as Server-Sent Events.
//!
//! Each text delta of the model is one event, and so is each tool call. The last
//! event has the stop reason. The Strands Agents SDK writes the agent.
//!
//! Run it with `cargo run --example streaming`, then:
//!
//! ```text
//! curl -N localhost:8080/invocations \
//!   -H 'X-Amzn-Bedrock-AgentCore-Runtime-Session-Id: local-session' \
//!   -H 'Accept: text/event-stream' \
//!   -d '{"prompt": "What is 1234.5 plus 678.25? Then tell me a short story."}'
//! ```

use bedrock_agentcore::runtime::{BedrockAgentCoreApp, Response};
use futures_util::StreamExt;
use serde::Deserialize;
use serde_json::json;
use strands::{Agent, AgentStreamEvent, ToolError, models::bedrock::BedrockModel, tool};

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

/// Add two numbers.
#[tool]
async fn add(
    /// The first number.
    a: f64,
    /// The second number.
    b: f64,
) -> Result<f64, ToolError> {
    Ok(a + b)
}

#[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| {
        let model = model.clone();
        async move {
            let mut agent = Agent::builder().model(model).tools([Add]).printer(false).build()?;
            // The stream runs after this function returns, so it owns the agent.
            // `agent.stream` borrows the agent, so it has a block of its own.
            let events = async_stream::try_stream! {
                {
                    let mut events = agent.stream(request.prompt);
                    while let Some(event) = events.next().await {
                        match event? {
                            AgentStreamEvent::ModelStreamUpdate(update) => {
                                if let Some(text) = update.text_delta() {
                                    yield json!({ "text": text });
                                }
                            }
                            AgentStreamEvent::BeforeToolCall(call) => {
                                yield json!({ "tool": call.tool_use.name, "input": call.tool_use.input });
                            }
                            AgentStreamEvent::AgentResult(result) => {
                                yield json!({ "done": result.stop_reason().to_string() });
                            }
                            _ => {}
                        }
                    }
                }
                agent.shutdown().await?;
            };
            Ok::<_, strands::Error>(Response::stream(events.map(|event: strands::Result<_>| event)))
        }
    };
    BedrockAgentCoreApp::builder().invocation(handle).build()?.run().await
}