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 pass_cutoff(&self) -> Option<f64> {
378        Some(self.threshold)
379    }
380
381    fn evaluate<'a>(
382        &'a self,
383        case: &'a Case,
384        trial: &'a Trial,
385    ) -> WasmBoxedFuture<'a, Result<Score, EvalError>> {
386        Box::pin(async move {
387            if let Some(score) = target_failed(&self.evaluator_id, trial) {
388                return Ok(score);
389            }
390            Ok(self.score(case, trial).await?)
391        })
392    }
393}
394
395/// Why an AgentCore target or evaluator failed.
396#[derive(Debug, thiserror::Error)]
397#[non_exhaustive]
398pub enum AgentCoreError {
399    /// The runtime ARN has no `runtime/<id>` part.
400    #[error("{0:?} is not an AgentCore runtime ARN")]
401    InvalidArn(String),
402    /// `InvokeAgentRuntime` failed.
403    #[error("InvokeAgentRuntime failed: {}", DisplayErrorContext(.0))]
404    Invoke(aws_sdk_bedrockagentcore::Error),
405    /// The reply body could not be read.
406    #[error("cannot read the runtime's reply: {0}")]
407    Body(#[from] aws_smithy_types::byte_stream::error::Error),
408    /// The reply is not `{"response": "..."}`.
409    #[error("the runtime replied without a response: {0}")]
410    Reply(String),
411    /// The trial has no session id.
412    #[error("the trial has no session id; AgentCore evaluators score trials of an AgentCoreTarget")]
413    NoSession,
414    /// The session's runtime is unknown.
415    #[error(
416        "no runtime log group for session {0:?}; use the AgentCore of the target or set runtime_log_group"
417    )]
418    UnknownRuntime(String),
419    /// A CloudWatch Logs Insights call failed.
420    #[error("CloudWatch Logs Insights failed: {}", DisplayErrorContext(.0))]
421    Query(aws_sdk_cloudwatchlogs::Error),
422    /// A Logs Insights query ended without results.
423    #[error("the CloudWatch Logs Insights query ended {0:?}")]
424    QueryEnded(QueryStatus),
425    /// The session's spans did not arrive in time.
426    #[error("no invoke_agent span of session {session_id:?} reached CloudWatch Logs in {waited:?}")]
427    NoSpans {
428        /// The session.
429        session_id: String,
430        /// How long it waited.
431        waited: Duration,
432    },
433    /// An `Evaluate` request could not be built.
434    #[error("cannot build the Evaluate request: {0}")]
435    Request(#[from] BuildError),
436    /// `Evaluate` failed.
437    #[error("Evaluate failed: {}", DisplayErrorContext(.0))]
438    Evaluate(aws_sdk_bedrockagentcore::Error),
439    /// An evaluation result is an error.
440    #[error("{evaluator} failed: {code}: {message}")]
441    Result {
442        /// The evaluator's name.
443        evaluator: String,
444        /// The error code.
445        code: String,
446        /// The error message.
447        message: String,
448    },
449    /// `Evaluate` returned no scored result.
450    #[error("{0} returned no score")]
451    NoScore(String),
452}
453
454impl From<AgentCoreError> for EvalError {
455    fn from(error: AgentCoreError) -> Self {
456        Self::Other(Box::new(error))
457    }
458}
459
460/// The runtime id in `arn`, the part after `runtime/`.
461fn runtime_id(arn: &str) -> Result<&str, AgentCoreError> {
462    arn.rsplit_once(":runtime/")
463        .map(|(_, id)| id)
464        .filter(|id| !id.is_empty() && !id.contains('/'))
465        .ok_or_else(|| AgentCoreError::InvalidArn(arn.to_owned()))
466}
467
468/// The log group of the runtime `arn`'s endpoint `qualifier`.
469fn runtime_log_group(arn: &str, qualifier: &str) -> Result<String, AgentCoreError> {
470    Ok(format!(
471        "/aws/bedrock-agentcore/runtimes/{}-{qualifier}",
472        runtime_id(arn)?
473    ))
474}
475
476/// The answer in a runtime's reply body.
477fn reply(body: &[u8]) -> Result<String, AgentCoreError> {
478    serde_json::from_slice::<Value>(body)
479        .ok()
480        .and_then(|reply| reply.get("response")?.as_str().map(str::to_owned))
481        .ok_or_else(|| AgentCoreError::Reply(String::from_utf8_lossy(body).into_owned()))
482}
483
484/// The Logs Insights query for the spans and events of `session_id`.
485fn spans_query(session_id: &str) -> String {
486    let session_id = session_id.replace('\\', "\\\\").replace('"', "\\\"");
487    format!(
488        "fields @timestamp, @message \
489         | filter ispresent(scope.name) and ispresent(attributes.session.id) \
490         | filter attributes.session.id = \"{session_id}\" \
491         | sort @timestamp asc | limit 500"
492    )
493}
494
495/// The `@message`s of a query's rows that are JSON objects.
496fn documents(rows: &[Vec<ResultField>]) -> Vec<Value> {
497    rows.iter()
498        .flatten()
499        .filter(|field| field.field() == Some("@message"))
500        .filter_map(ResultField::value)
501        .filter(|message| message.starts_with('{'))
502        .filter_map(|message| serde_json::from_str(message).ok())
503        .collect()
504}
505
506/// Whether `span` is an agent invocation.
507fn is_invocation(span: &Value) -> bool {
508    span.get("name")
509        .and_then(Value::as_str)
510        .is_some_and(|name| name.starts_with("invoke_agent"))
511}
512
513fn has_invocation(spans: &[Value]) -> bool {
514    invocations(spans) > 0
515}
516
517/// How many agent invocations the spans hold.
518fn invocations(spans: &[Value]) -> usize {
519    spans.iter().filter(|span| is_invocation(span)).count()
520}
521
522/// Whether the spans are all in: one invocation per turn arrived, and the
523/// count stayed the same since the `previous` query.
524fn settled(previous: Option<usize>, spans: &[Value], turns: usize) -> bool {
525    invocations(spans) >= turns && previous == Some(spans.len())
526}
527
528/// The trace of the last agent invocation: the one an expected answer is
529/// compared with.
530fn last_trace_id(spans: &[Value]) -> Option<&str> {
531    spans
532        .iter()
533        .rev()
534        .filter(|span| is_invocation(span))
535        .find_map(|span| span.get("traceId")?.as_str())
536}
537
538/// The case's references for `Evaluate`: assertions and the tool trajectory
539/// for the session, the expected answer for its last trace. Only what the
540/// case has.
541fn reference_inputs(
542    case: &Case,
543    session_id: &str,
544    trace_id: Option<&str>,
545) -> Result<Vec<EvaluationReferenceInput>, BuildError> {
546    let context = |trace_id: Option<&str>| -> Result<Context, BuildError> {
547        Ok(Context::SpanContext(
548            SpanContext::builder()
549                .session_id(session_id)
550                .set_trace_id(trace_id.map(str::to_owned))
551                .build()?,
552        ))
553    };
554    let mut references = Vec::new();
555    if !case.assertions.is_empty() || case.trajectory.is_some() {
556        let assertions = case
557            .assertions
558            .iter()
559            .map(|assertion| EvaluationContent::Text(assertion.clone()))
560            .collect::<Vec<_>>();
561        let trajectory = case.trajectory.as_ref().map(|calls| {
562            EvaluationExpectedTrajectory::builder()
563                .set_tool_names(Some(calls.iter().map(|call| call.name.clone()).collect()))
564                .build()
565        });
566        references.push(
567            EvaluationReferenceInput::builder()
568                .context(context(None)?)
569                .set_assertions((!assertions.is_empty()).then_some(assertions))
570                .set_expected_trajectory(trajectory)
571                .build(),
572        );
573    }
574    if let (Some(expected), Some(trace_id)) = (&case.expected, trace_id) {
575        references.push(
576            EvaluationReferenceInput::builder()
577                .context(context(Some(trace_id))?)
578                .expected_response(EvaluationContent::Text(expected.clone()))
579                .build(),
580        );
581    }
582    Ok(references)
583}
584
585/// The score of `results`: their mean value against `threshold`, their
586/// labels and explanations joined.
587fn score(
588    evaluator: &str,
589    results: &[EvaluationResultContent],
590    threshold: f64,
591) -> Result<Score, AgentCoreError> {
592    if let Some(failed) = results
593        .iter()
594        .find(|result| result.error_code().is_some() || result.error_message().is_some())
595    {
596        return Err(AgentCoreError::Result {
597            evaluator: evaluator.to_owned(),
598            code: failed.error_code().unwrap_or("error").to_owned(),
599            message: failed.error_message().unwrap_or_default().to_owned(),
600        });
601    }
602    let values: Vec<f64> = results.iter().filter_map(|result| result.value()).collect();
603    if values.is_empty() {
604        return Err(AgentCoreError::NoScore(evaluator.to_owned()));
605    }
606    let mean = values.iter().sum::<f64>() / values.len() as f64;
607    let join = |parts: Vec<&str>, separator| (!parts.is_empty()).then(|| parts.join(separator));
608    let mut score = Score::new(evaluator, mean, mean >= threshold);
609    score.label = join(results.iter().filter_map(|r| r.label()).collect(), "; ");
610    score.explanation = join(
611        results.iter().filter_map(|r| r.explanation()).collect(),
612        "\n\n",
613    );
614    Ok(score)
615}
616
617/// `value` as a Smithy document.
618fn document(value: &Value) -> Document {
619    match value {
620        Value::Null => Document::Null,
621        Value::Bool(value) => Document::Bool(*value),
622        Value::Number(number) => Document::Number(if let Some(n) = number.as_u64() {
623            Number::PosInt(n)
624        } else if let Some(n) = number.as_i64() {
625            Number::NegInt(n)
626        } else {
627            Number::Float(number.as_f64().unwrap_or_default())
628        }),
629        Value::String(value) => Document::String(value.clone()),
630        Value::Array(values) => Document::Array(values.iter().map(document).collect()),
631        Value::Object(map) => Document::Object(
632            map.iter()
633                .map(|(key, value)| (key.clone(), document(value)))
634                .collect(),
635        ),
636    }
637}
638
639/// Seconds since the Unix epoch.
640fn epoch_seconds(time: SystemTime) -> i64 {
641    time.duration_since(UNIX_EPOCH)
642        .map_or(0, |elapsed| elapsed.as_secs() as i64)
643}