Skip to main content

rig_evals/
agentcore.rs

1//! AWS Bedrock AgentCore: a deployed runtime as a [`Target`], and AgentCore
2//! Evaluations' evaluators as [`Evaluator`]s.
3//!
4//! The flow of AgentCore's on-demand evaluation: invoke the runtime in a
5//! fresh session, read the session's spans from CloudWatch Logs once they
6//! arrive, and send them to the `Evaluate` API.
7
8use std::collections::HashMap;
9use std::sync::{Arc, Mutex, PoisonError};
10use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
11
12use aws_sdk_bedrockagentcore::types::{
13    Context, EvaluationContent, EvaluationExpectedTrajectory, EvaluationInput,
14    EvaluationReferenceInput, EvaluationResultContent, SpanContext,
15};
16use aws_sdk_cloudwatchlogs::types::{QueryStatus, ResultField};
17use aws_smithy_types::error::display::DisplayErrorContext;
18use aws_smithy_types::error::operation::BuildError;
19use aws_smithy_types::{Blob, Document, Number};
20use rig_core::wasm_compat::WasmBoxedFuture;
21use serde_json::{Value, json};
22
23use crate::evaluators::target_failed;
24use crate::{Case, EvalError, Evaluator, Score, Target, TargetError, TargetOutput, Trial};
25
26#[cfg(test)]
27mod tests;
28
29/// The Transaction Search log group AgentCore Observability writes spans to.
30const SPANS_LOG_GROUP: &str = "aws/spans";
31
32/// How far before a trial's start the span query looks, for clock skew.
33const QUERY_MARGIN: Duration = Duration::from_secs(300);
34
35/// The AWS clients AgentCore targets and evaluators share, and the spans
36/// downloaded so far, so several evaluators of one run download them once.
37#[derive(Debug, Clone)]
38pub struct AgentCore {
39    runtime: aws_sdk_bedrockagentcore::Client,
40    logs: aws_sdk_cloudwatchlogs::Client,
41    state: Arc<Mutex<State>>,
42}
43
44/// What an experiment learns about its sessions.
45// ponytail: grows with the sessions run; one experiment's worth is small.
46#[derive(Debug, Default)]
47struct State {
48    /// Each session's runtime log group, recorded by the target.
49    log_groups: HashMap<String, String>,
50    /// Each session's spans, once downloaded.
51    spans: HashMap<String, Arc<Vec<Value>>>,
52}
53
54impl AgentCore {
55    /// Clients from the standard AWS configuration: the environment, the
56    /// shared config files, an IAM role.
57    pub async fn from_env() -> Self {
58        Self::new(&aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await)
59    }
60
61    /// Clients from `config`.
62    pub fn new(config: &aws_config::SdkConfig) -> Self {
63        Self {
64            runtime: aws_sdk_bedrockagentcore::Client::new(config),
65            logs: aws_sdk_cloudwatchlogs::Client::new(config),
66            state: Arc::default(),
67        }
68    }
69
70    /// The runtime `runtime_arn` (an AgentCore Runtime agent speaking the
71    /// HTTP protocol) as a target.
72    pub fn target(&self, runtime_arn: impl Into<String>) -> AgentCoreTarget {
73        AgentCoreTarget {
74            agentcore: self.clone(),
75            runtime_arn: runtime_arn.into(),
76            qualifier: None,
77        }
78    }
79
80    /// The AgentCore evaluator `evaluator_id`: a built-in such as
81    /// `Builtin.Correctness`, or a custom evaluator's id.
82    pub fn evaluator(&self, evaluator_id: impl Into<String>) -> AgentCoreEvaluator {
83        AgentCoreEvaluator {
84            agentcore: self.clone(),
85            evaluator_id: evaluator_id.into(),
86            threshold: 0.5,
87            ingestion_timeout: Duration::from_secs(300),
88            poll_interval: Duration::from_secs(10),
89            runtime_log_group: None,
90        }
91    }
92
93    fn state(&self) -> std::sync::MutexGuard<'_, State> {
94        self.state.lock().unwrap_or_else(PoisonError::into_inner)
95    }
96
97    /// The spans of `session_id`, from the cache or CloudWatch Logs.
98    async fn spans(
99        &self,
100        session_id: &str,
101        log_group: &str,
102        since: SystemTime,
103        timeout: Duration,
104        poll_interval: Duration,
105    ) -> Result<Arc<Vec<Value>>, AgentCoreError> {
106        if let Some(spans) = self.state().spans.get(session_id) {
107            return Ok(spans.clone());
108        }
109        let started = Instant::now();
110        let mut previous = None;
111        let spans = loop {
112            let spans = self.query(session_id, log_group, since).await?;
113            let last_chance = started.elapsed().saturating_add(poll_interval) > timeout;
114            if settled(previous, &spans) || (last_chance && has_invocation(&spans)) {
115                break spans;
116            }
117            if last_chance {
118                return Err(AgentCoreError::NoSpans {
119                    session_id: session_id.to_owned(),
120                    waited: timeout,
121                });
122            }
123            previous = Some(spans.len());
124            tokio::time::sleep(poll_interval).await;
125        };
126        let spans = Arc::new(spans);
127        self.state()
128            .spans
129            .insert(session_id.to_owned(), spans.clone());
130        Ok(spans)
131    }
132
133    /// One Logs Insights query for the spans of `session_id`.
134    async fn query(
135        &self,
136        session_id: &str,
137        log_group: &str,
138        since: SystemTime,
139    ) -> Result<Vec<Value>, AgentCoreError> {
140        let started = self
141            .logs
142            .start_query()
143            .log_group_names(SPANS_LOG_GROUP)
144            .log_group_names(log_group)
145            .start_time(epoch_seconds(since))
146            .end_time(epoch_seconds(SystemTime::now()) + 60)
147            .query_string(spans_query(session_id))
148            .send()
149            .await
150            .map_err(|error| AgentCoreError::Query(error.into()))?;
151        let query_id = started.query_id().unwrap_or_default();
152        loop {
153            let results = self
154                .logs
155                .get_query_results()
156                .query_id(query_id)
157                .send()
158                .await
159                .map_err(|error| AgentCoreError::Query(error.into()))?;
160            match results.status() {
161                Some(QueryStatus::Complete) => return Ok(documents(results.results())),
162                Some(QueryStatus::Running | QueryStatus::Scheduled) | None => {
163                    tokio::time::sleep(Duration::from_secs(1)).await;
164                }
165                Some(status) => return Err(AgentCoreError::QueryEnded(status.clone())),
166            }
167        }
168    }
169}
170
171/// A runtime on AgentCore Runtime; see [`AgentCore::target`].
172///
173/// Each run invokes the runtime with `{"prompt": <input>}` in a new
174/// session and answers the reply's `response`. The trial carries the session
175/// id, which [`AgentCoreEvaluator`]s read the run's spans by.
176#[derive(Debug, Clone)]
177pub struct AgentCoreTarget {
178    agentcore: AgentCore,
179    runtime_arn: String,
180    qualifier: Option<String>,
181}
182
183impl AgentCoreTarget {
184    /// Invoke this endpoint of the runtime instead of `DEFAULT`.
185    #[must_use]
186    pub fn qualifier(mut self, qualifier: impl Into<String>) -> Self {
187        self.qualifier = Some(qualifier.into());
188        self
189    }
190
191    async fn invoke(&self, prompt: &str) -> Result<TargetOutput, AgentCoreError> {
192        let log_group = runtime_log_group(
193            &self.runtime_arn,
194            self.qualifier.as_deref().unwrap_or("DEFAULT"),
195        )?;
196        // AgentCore requires at least 33 characters.
197        let session_id = format!("rig-evals-{}", uuid::Uuid::new_v4());
198        self.agentcore
199            .state()
200            .log_groups
201            .insert(session_id.clone(), log_group);
202        let output = self
203            .agentcore
204            .runtime
205            .invoke_agent_runtime()
206            .agent_runtime_arn(&self.runtime_arn)
207            .set_qualifier(self.qualifier.clone())
208            .runtime_session_id(&session_id)
209            .content_type("application/json")
210            .accept("application/json")
211            .payload(Blob::new(json!({ "prompt": prompt }).to_string()))
212            .send()
213            .await
214            .map_err(|error| AgentCoreError::Invoke(error.into()))?;
215        let body = output.response.collect().await?.into_bytes();
216        Ok(TargetOutput::new(reply(&body)?).with_session_id(session_id))
217    }
218}
219
220impl Target for AgentCoreTarget {
221    fn run<'a>(&'a self, case: &'a Case) -> WasmBoxedFuture<'a, Result<TargetOutput, TargetError>> {
222        Box::pin(async move { Ok(self.invoke(&case.input).await?) })
223    }
224}
225
226/// An AgentCore Evaluations evaluator; see [`AgentCore::evaluator`].
227///
228/// Scores trials that ran in an AgentCore session (from an
229/// [`AgentCoreTarget`], or any trial with a session id and a
230/// [`runtime_log_group`](Self::runtime_log_group)): it waits for the
231/// session's spans in CloudWatch Logs, sends them to `Evaluate` with the
232/// case's references (expected answer, tool trajectory, assertions), and
233/// scores the mean of the results; trace-level evaluators give one per trace.
234/// Named after the evaluator id.
235#[derive(Debug, Clone)]
236pub struct AgentCoreEvaluator {
237    agentcore: AgentCore,
238    evaluator_id: String,
239    threshold: f64,
240    ingestion_timeout: Duration,
241    poll_interval: Duration,
242    runtime_log_group: Option<String>,
243}
244
245impl AgentCoreEvaluator {
246    /// Pass when the mean value is at least `threshold` (0.5 unless set).
247    #[must_use]
248    pub fn threshold(mut self, threshold: f64) -> Self {
249        self.threshold = threshold;
250        self
251    }
252
253    /// How long to wait for a run's spans to reach CloudWatch Logs (5
254    /// minutes unless set).
255    #[must_use]
256    pub fn ingestion_timeout(mut self, timeout: Duration) -> Self {
257        self.ingestion_timeout = timeout;
258        self
259    }
260
261    /// How often to query for the spans while waiting (10 seconds unless
262    /// set).
263    #[must_use]
264    pub fn poll_interval(mut self, interval: Duration) -> Self {
265        self.poll_interval = interval;
266        self
267    }
268
269    /// The runtime's log group, such as
270    /// `/aws/bedrock-agentcore/runtimes/<runtime-id>-DEFAULT`: for trials
271    /// that did not come from an [`AgentCoreTarget`] of the same
272    /// [`AgentCore`].
273    #[must_use]
274    pub fn runtime_log_group(mut self, log_group: impl Into<String>) -> Self {
275        self.runtime_log_group = Some(log_group.into());
276        self
277    }
278
279    async fn score(&self, case: &Case, trial: &Trial) -> Result<Score, AgentCoreError> {
280        let session_id = trial
281            .session_id
282            .as_deref()
283            .ok_or(AgentCoreError::NoSession)?;
284        let log_group = match &self.runtime_log_group {
285            Some(log_group) => log_group.clone(),
286            None => self
287                .agentcore
288                .state()
289                .log_groups
290                .get(session_id)
291                .cloned()
292                .ok_or_else(|| AgentCoreError::UnknownRuntime(session_id.to_owned()))?,
293        };
294        let since = SystemTime::now()
295            .checked_sub(trial.latency.saturating_add(QUERY_MARGIN))
296            .unwrap_or(UNIX_EPOCH);
297        let spans = self
298            .agentcore
299            .spans(
300                session_id,
301                &log_group,
302                since,
303                self.ingestion_timeout,
304                self.poll_interval,
305            )
306            .await?;
307        let references = reference_inputs(case, session_id, last_trace_id(&spans))?;
308        let output = self
309            .agentcore
310            .runtime
311            .evaluate()
312            .evaluator_id(&self.evaluator_id)
313            .evaluation_input(EvaluationInput::SessionSpans(
314                spans.iter().map(document).collect(),
315            ))
316            .set_evaluation_reference_inputs((!references.is_empty()).then_some(references))
317            .send()
318            .await
319            .map_err(|error| AgentCoreError::Evaluate(error.into()))?;
320        score(
321            &self.evaluator_id,
322            output.evaluation_results(),
323            self.threshold,
324        )
325    }
326}
327
328impl Evaluator for AgentCoreEvaluator {
329    fn name(&self) -> &str {
330        &self.evaluator_id
331    }
332
333    fn evaluate<'a>(
334        &'a self,
335        case: &'a Case,
336        trial: &'a Trial,
337    ) -> WasmBoxedFuture<'a, Result<Score, EvalError>> {
338        Box::pin(async move {
339            if let Some(score) = target_failed(&self.evaluator_id, trial) {
340                return Ok(score);
341            }
342            Ok(self.score(case, trial).await?)
343        })
344    }
345}
346
347/// Why an AgentCore target or evaluator failed.
348#[derive(Debug, thiserror::Error)]
349#[non_exhaustive]
350pub enum AgentCoreError {
351    /// The runtime ARN has no `runtime/<id>` part.
352    #[error("{0:?} is not an AgentCore runtime ARN")]
353    InvalidArn(String),
354    /// `InvokeAgentRuntime` failed.
355    #[error("InvokeAgentRuntime failed: {}", DisplayErrorContext(.0))]
356    Invoke(aws_sdk_bedrockagentcore::Error),
357    /// The reply body could not be read.
358    #[error("cannot read the runtime's reply: {0}")]
359    Body(#[from] aws_smithy_types::byte_stream::error::Error),
360    /// The reply is not `{"response": "..."}`.
361    #[error("the runtime replied without a response: {0}")]
362    Reply(String),
363    /// The trial has no session id.
364    #[error("the trial has no session id; AgentCore evaluators score trials of an AgentCoreTarget")]
365    NoSession,
366    /// The session's runtime is unknown.
367    #[error(
368        "no runtime log group for session {0:?}; use the AgentCore of the target or set runtime_log_group"
369    )]
370    UnknownRuntime(String),
371    /// A CloudWatch Logs Insights call failed.
372    #[error("CloudWatch Logs Insights failed: {}", DisplayErrorContext(.0))]
373    Query(aws_sdk_cloudwatchlogs::Error),
374    /// A Logs Insights query ended without results.
375    #[error("the CloudWatch Logs Insights query ended {0:?}")]
376    QueryEnded(QueryStatus),
377    /// The session's spans did not arrive in time.
378    #[error("no invoke_agent span of session {session_id:?} reached CloudWatch Logs in {waited:?}")]
379    NoSpans {
380        /// The session.
381        session_id: String,
382        /// How long it waited.
383        waited: Duration,
384    },
385    /// An `Evaluate` request could not be built.
386    #[error("cannot build the Evaluate request: {0}")]
387    Request(#[from] BuildError),
388    /// `Evaluate` failed.
389    #[error("Evaluate failed: {}", DisplayErrorContext(.0))]
390    Evaluate(aws_sdk_bedrockagentcore::Error),
391    /// An evaluation result is an error.
392    #[error("{evaluator} failed: {code}: {message}")]
393    Result {
394        /// The evaluator's name.
395        evaluator: String,
396        /// The error code.
397        code: String,
398        /// The error message.
399        message: String,
400    },
401    /// `Evaluate` returned no scored result.
402    #[error("{0} returned no score")]
403    NoScore(String),
404}
405
406impl From<AgentCoreError> for EvalError {
407    fn from(error: AgentCoreError) -> Self {
408        Self::Other(Box::new(error))
409    }
410}
411
412/// The runtime id in `arn`, the part after `runtime/`.
413fn runtime_id(arn: &str) -> Result<&str, AgentCoreError> {
414    arn.rsplit_once(":runtime/")
415        .map(|(_, id)| id)
416        .filter(|id| !id.is_empty() && !id.contains('/'))
417        .ok_or_else(|| AgentCoreError::InvalidArn(arn.to_owned()))
418}
419
420/// The log group of the runtime `arn`'s endpoint `qualifier`.
421fn runtime_log_group(arn: &str, qualifier: &str) -> Result<String, AgentCoreError> {
422    Ok(format!(
423        "/aws/bedrock-agentcore/runtimes/{}-{qualifier}",
424        runtime_id(arn)?
425    ))
426}
427
428/// The answer in a runtime's reply body.
429fn reply(body: &[u8]) -> Result<String, AgentCoreError> {
430    serde_json::from_slice::<Value>(body)
431        .ok()
432        .and_then(|reply| reply.get("response")?.as_str().map(str::to_owned))
433        .ok_or_else(|| AgentCoreError::Reply(String::from_utf8_lossy(body).into_owned()))
434}
435
436/// The Logs Insights query for the spans and events of `session_id`.
437fn spans_query(session_id: &str) -> String {
438    let session_id = session_id.replace('\\', "\\\\").replace('"', "\\\"");
439    format!(
440        "fields @timestamp, @message \
441         | filter ispresent(scope.name) and ispresent(attributes.session.id) \
442         | filter attributes.session.id = \"{session_id}\" \
443         | sort @timestamp asc | limit 500"
444    )
445}
446
447/// The `@message`s of a query's rows that are JSON objects.
448fn documents(rows: &[Vec<ResultField>]) -> Vec<Value> {
449    rows.iter()
450        .flatten()
451        .filter(|field| field.field() == Some("@message"))
452        .filter_map(ResultField::value)
453        .filter(|message| message.starts_with('{'))
454        .filter_map(|message| serde_json::from_str(message).ok())
455        .collect()
456}
457
458/// Whether `span` is an agent invocation.
459fn is_invocation(span: &Value) -> bool {
460    span.get("name")
461        .and_then(Value::as_str)
462        .is_some_and(|name| name.starts_with("invoke_agent"))
463}
464
465fn has_invocation(spans: &[Value]) -> bool {
466    spans.iter().any(is_invocation)
467}
468
469/// Whether the spans are all in: an invocation arrived, and the count stayed
470/// the same since the `previous` query.
471fn settled(previous: Option<usize>, spans: &[Value]) -> bool {
472    has_invocation(spans) && previous == Some(spans.len())
473}
474
475/// The trace of the last agent invocation: the one an expected answer is
476/// compared with.
477fn last_trace_id(spans: &[Value]) -> Option<&str> {
478    spans
479        .iter()
480        .rev()
481        .filter(|span| is_invocation(span))
482        .find_map(|span| span.get("traceId")?.as_str())
483}
484
485/// The case's references for `Evaluate`: assertions and the tool trajectory
486/// for the session, the expected answer for its last trace. Only what the
487/// case has.
488fn reference_inputs(
489    case: &Case,
490    session_id: &str,
491    trace_id: Option<&str>,
492) -> Result<Vec<EvaluationReferenceInput>, BuildError> {
493    let context = |trace_id: Option<&str>| -> Result<Context, BuildError> {
494        Ok(Context::SpanContext(
495            SpanContext::builder()
496                .session_id(session_id)
497                .set_trace_id(trace_id.map(str::to_owned))
498                .build()?,
499        ))
500    };
501    let mut references = Vec::new();
502    if !case.assertions.is_empty() || case.trajectory.is_some() {
503        let assertions = case
504            .assertions
505            .iter()
506            .map(|assertion| EvaluationContent::Text(assertion.clone()))
507            .collect::<Vec<_>>();
508        let trajectory = case.trajectory.as_ref().map(|calls| {
509            EvaluationExpectedTrajectory::builder()
510                .set_tool_names(Some(calls.iter().map(|call| call.name.clone()).collect()))
511                .build()
512        });
513        references.push(
514            EvaluationReferenceInput::builder()
515                .context(context(None)?)
516                .set_assertions((!assertions.is_empty()).then_some(assertions))
517                .set_expected_trajectory(trajectory)
518                .build(),
519        );
520    }
521    if let (Some(expected), Some(trace_id)) = (&case.expected, trace_id) {
522        references.push(
523            EvaluationReferenceInput::builder()
524                .context(context(Some(trace_id))?)
525                .expected_response(EvaluationContent::Text(expected.clone()))
526                .build(),
527        );
528    }
529    Ok(references)
530}
531
532/// The score of `results`: their mean value against `threshold`, their
533/// labels and explanations joined.
534fn score(
535    evaluator: &str,
536    results: &[EvaluationResultContent],
537    threshold: f64,
538) -> Result<Score, AgentCoreError> {
539    if let Some(failed) = results
540        .iter()
541        .find(|result| result.error_code().is_some() || result.error_message().is_some())
542    {
543        return Err(AgentCoreError::Result {
544            evaluator: evaluator.to_owned(),
545            code: failed.error_code().unwrap_or("error").to_owned(),
546            message: failed.error_message().unwrap_or_default().to_owned(),
547        });
548    }
549    let values: Vec<f64> = results.iter().filter_map(|result| result.value()).collect();
550    if values.is_empty() {
551        return Err(AgentCoreError::NoScore(evaluator.to_owned()));
552    }
553    let mean = values.iter().sum::<f64>() / values.len() as f64;
554    let join = |parts: Vec<&str>, separator| (!parts.is_empty()).then(|| parts.join(separator));
555    let mut score = Score::new(evaluator, mean, mean >= threshold);
556    score.label = join(results.iter().filter_map(|r| r.label()).collect(), "; ");
557    score.explanation = join(
558        results.iter().filter_map(|r| r.explanation()).collect(),
559        "\n\n",
560    );
561    Ok(score)
562}
563
564/// `value` as a Smithy document.
565fn document(value: &Value) -> Document {
566    match value {
567        Value::Null => Document::Null,
568        Value::Bool(value) => Document::Bool(*value),
569        Value::Number(number) => Document::Number(if let Some(n) = number.as_u64() {
570            Number::PosInt(n)
571        } else if let Some(n) = number.as_i64() {
572            Number::NegInt(n)
573        } else {
574            Number::Float(number.as_f64().unwrap_or_default())
575        }),
576        Value::String(value) => Document::String(value.clone()),
577        Value::Array(values) => Document::Array(values.iter().map(document).collect()),
578        Value::Object(map) => Document::Object(
579            map.iter()
580                .map(|(key, value)| (key.clone(), document(value)))
581                .collect(),
582        ),
583    }
584}
585
586/// Seconds since the Unix epoch.
587fn epoch_seconds(time: SystemTime) -> i64 {
588    time.duration_since(UNIX_EPOCH)
589        .map_or(0, |elapsed| elapsed.as_secs() as i64)
590}