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