rig-agentcore 0.47.10

Run a Rig agent on AWS Bedrock AgentCore Runtime: the HTTP protocol contract (/invocations, /ping), sessions, streaming and traces AgentCore Observability and Evaluations read.
Documentation
//! Serve a Rig agent on the AgentCore Runtime HTTP contract, locally.
//!
//! Listens on `PORT` (default 8080), the port AgentCore sends to. Without
//! AWS, a scripted model answers each invocation with the next numbered
//! reply, never running out, and logs how many messages each request carries, so a
//! session's history shows up as it grows. Set `RIG_MODEL` to answer with a
//! live model instead:
//!
//! - `RIG_MODEL=opencode-go/<model>` runs on OpenCode Go, with the key in
//!   `OPENCODE_GO_API_KEY`.
//! - `RIG_MODEL=<id>` runs on OpenRouter, with the key in `OPENROUTER_API_KEY`.
//!   `OPENROUTER_MODEL` is read when `RIG_MODEL` is unset.
//!
//! ```sh
//! RIG_MODEL=opencode-go/glm-5.3 OPENCODE_GO_API_KEY=... PORT=3200 \
//!     cargo run -p rig-agentcore --example serve
//! ```
//!
//! ```sh
//! PORT=3200 cargo run -p rig-agentcore --example serve
//! ```
//!
//! In another shell, with the `PORT` above (8080 when unset):
//!
//! ```sh
//! # Health check: {"status":"Healthy"}
//! curl -s localhost:3200/ping
//!
//! # One JSON answer: {"response":"...","status":"success"}
//! curl -s localhost:3200/invocations -H 'content-type: application/json' \
//!   -d '{"prompt":"Hi, I am Ana."}'
//!
//! # The same contract as server-sent events. The session header names the
//! # conversation, so this call sees the first one.
//! curl -sN localhost:3200/invocations \
//!   -H 'content-type: application/json' -H 'accept: text/event-stream' \
//!   -H 'X-Amzn-Bedrock-AgentCore-Runtime-Session-Id: demo-session-1234567890' \
//!   -d '{"prompt":"What is my name?"}'
//! ```
//!
//! A real deployment builds this app as an ARM64 container image, pushes it
//! to Amazon ECR and runs it on AgentCore Runtime, which then sends the same
//! requests. This example creates no AWS resources.
//!
//! Traces: set `OTEL_EXPORTER_OTLP_ENDPOINT` (for example `http://127.0.0.1:4318`)
//! to export spans over OTLP, such as to the Jaeger container in rig-otel's
//! example. Unset, no telemetry is set up, so nothing is exported.

use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

use rig_agent::AgentBuilder;
use rig_agentcore::AgentCoreApp;
use rig_core::DynModel;
use rig_core::completion::CompletionRequest;
use rig_core::driver::{Exchange, Model, Opening, Transport};
use rig_core::operation::Completion;
use rig_core::providers::{opencode, openrouter};
use rig_core::test_utils::{MockCompletionModel, MockFrame, MockScript, MockStreamEvent, MockTurn};
use rig_core::wire::Mode;
use rig_otel::Telemetry;

/// Numbers the scripted replies. Rig's mock takes its turns up front, so each
/// request gets a fresh one-turn mock, which keeps the script endless.
#[derive(Clone, Default)]
struct Scripted {
    replies: Arc<AtomicUsize>,
}

impl Transport<MockScript> for Scripted {
    fn send(&self, request: CompletionRequest, exchange: Exchange) -> Opening<MockFrame> {
        // The messages this call sends: the prompt plus the session's history.
        eprintln!(
            "scripted model: {} message(s) in the request",
            request.chat_history.len()
        );
        let n = self.replies.fetch_add(1, Ordering::Relaxed) + 1;
        let text = format!("Scripted reply {n}.");
        match exchange.mode {
            Mode::Unary => MockCompletionModel::from_turns([MockTurn::text(text)])
                .transport
                .send(request, exchange),
            Mode::Streaming => MockCompletionModel::from_stream_turns([vec![
                MockStreamEvent::text(text),
                MockStreamEvent::final_response_with_default_usage(),
            ]])
            .transport
            .send(request, exchange),
        }
    }
}

fn scripted_model() -> Model<MockScript, Scripted> {
    Model::new(MockScript::default(), Scripted::default())
}

const PREAMBLE: &str = "You are a concise, friendly assistant.";

/// OTLP telemetry when `OTEL_EXPORTER_OTLP_ENDPOINT` is set. The guard flushes
/// on drop, so it is kept until `main` returns.
fn telemetry() -> anyhow::Result<Option<Telemetry>> {
    if std::env::var_os("OTEL_EXPORTER_OTLP_ENDPOINT").is_none() {
        return Ok(None);
    }
    Ok(Some(rig_otel::init()?))
}

/// A live model from `RIG_MODEL` (or `OPENROUTER_MODEL`), with a label for the
/// log line. `None` when neither is set.
fn live_model() -> anyhow::Result<Option<(DynModel<Completion>, String)>> {
    let Ok(id) = std::env::var("RIG_MODEL").or_else(|_| std::env::var("OPENROUTER_MODEL")) else {
        return Ok(None);
    };
    if let Some(model) = id.strip_prefix("opencode-go/") {
        let key = std::env::var("OPENCODE_GO_API_KEY")?;
        let label = format!("OpenCode Go {model}");
        return Ok(Some((
            opencode::go_new(key).completion(model).into(),
            label,
        )));
    }
    let client = openrouter::from_env()?;
    Ok(Some((client.chat(&id).into(), format!("OpenRouter {id}"))))
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let _telemetry = telemetry()?;

    match live_model()? {
        Some((model, label)) => {
            println!("model: {label}");
            let agent = AgentBuilder::new(model)
                .name("Rig AgentCore helper")
                .preamble(PREAMBLE)
                .build();
            AgentCoreApp::new(agent).serve().await?;
        }
        None => {
            println!("model: scripted (endless)");
            let agent = AgentBuilder::new(scripted_model())
                .name("Rig AgentCore helper")
                .preamble(PREAMBLE)
                .build();
            AgentCoreApp::new(agent).serve().await?;
        }
    }
    Ok(())
}