trusty_code/llm/bedrock.rs
1//! AWS Bedrock Converse transport — a thin bridge onto `trusty_common::inference`
2//! (#2407 migration).
3//!
4//! Why: the entire Bedrock Converse wire integration (region resolution, the AWS
5//! credential chain, the `ChatRequest`/`ChatResponse` <-> Converse conversion,
6//! and the `cachePoint` prompt-cache translation) moved into the shared
7//! `trusty_common::inference::bedrock` adapter in #2407, so every consumer shares
8//! ONE implementation instead of tcode owning a private ~1000-SLOC copy. This
9//! module is what remains in tcode: a thin `LlmClientTrait`-shaped wrapper that
10//! bridges tcode's wire types to the shared adapter at exactly one seam (reusing
11//! `super::convert`, the same field-by-field bridge #2406 established for the
12//! OpenAI-compatible transport) — zero local Bedrock/Converse logic.
13//! What: [`BedrockChatClient`] wraps a
14//! [`trusty_common::inference::BedrockAdapter`]. `chat` converts the request via
15//! [`super::convert::to_shared_request`] (passing the FULL `bedrock/`-prefixed
16//! slug as the wire model — the shared adapter strips the prefix before the AWS
17//! call and keeps it for telemetry), delegates to the shared adapter, maps its
18//! [`trusty_common::inference::InferenceError`] back to [`LlmError`] via
19//! [`super::convert::map_error`], and converts the response via
20//! [`super::convert::from_shared_response`]. The shared adapter constructs its
21//! AWS client lazily on first `chat`, so [`Self::from_env`]/[`Self::new`] touch
22//! no AWS credentials. [`Self::new`]/[`Self::region`] are thin passthroughs kept
23//! for public-API compatibility with the pre-#2407 local transport (no in-tree
24//! caller uses them post-migration, but this is a published rlib crate and the
25//! surface removal would otherwise be undocumented/silent).
26//! Test: `bedrock::tests::*` (offline construction) plus the shared adapter's own
27//! conversion + `#[ignore]`-gated live coverage in
28//! `trusty_common::inference::bedrock`.
29
30use trusty_common::inference::{BedrockAdapter, InferenceAdapter};
31
32use super::convert::{from_shared_response, map_error, to_shared_request};
33use super::error::LlmError;
34use super::request::ChatRequest;
35use super::response::ChatResponse;
36
37/// AWS Bedrock Converse transport, backed by the shared inference adapter.
38///
39/// Why: satisfies the same `chat(&ChatRequest) -> Result<ChatResponse, ..>`
40/// contract every other tcode transport exposes, so `DispatchingLlmClient`
41/// (`super::dispatch`) can route `bedrock/*` slugs here without any caller
42/// knowing the backend differs — while the Converse mechanics live in
43/// `trusty_common::inference::bedrock`, not in this crate.
44/// What: holds a shared [`BedrockAdapter`] (which owns the resolved region and a
45/// lazily-built AWS client). `Debug` so `DispatchingLlmClient`'s
46/// `OnceCell<BedrockChatClient>` can derive it.
47/// Test: `bedrock::tests::from_env_constructs_offline`.
48#[derive(Debug)]
49pub struct BedrockChatClient {
50 inner: BedrockAdapter,
51}
52
53impl BedrockChatClient {
54 /// Construct a `BedrockChatClient` for an explicit (or default) region.
55 ///
56 /// Why: public-API compatibility passthrough — the pre-#2407 local transport
57 /// exposed this constructor; no in-tree caller uses it today (everything goes
58 /// through [`Self::from_env`] via `DispatchingLlmClient`), but this is a
59 /// published rlib crate, so the constructor is kept rather than silently
60 /// dropped.
61 /// What: wraps [`BedrockAdapter::new`] with `region`. Async + `Result` to
62 /// match the pre-migration signature; never actually fails.
63 /// Test: `bedrock::tests::new_constructs_offline`.
64 pub async fn new(region: Option<&str>) -> Result<Self, LlmError> {
65 Ok(Self {
66 inner: BedrockAdapter::new(region),
67 })
68 }
69
70 /// Construct a `BedrockChatClient` from the environment.
71 ///
72 /// Why: the convenience entry point `DispatchingLlmClient` lazily calls on
73 /// the first `bedrock/*` request. Region resolves from
74 /// `TRUSTY_AWS_REGION`/`AWS_REGION`/default; credentials come from the AWS
75 /// chain, resolved lazily on the first `chat`, so this never touches AWS.
76 /// What: delegates to [`Self::new`] with `region: None`.
77 /// Test: `bedrock::tests::from_env_constructs_offline`.
78 pub async fn from_env() -> Result<Self, LlmError> {
79 Self::new(None).await
80 }
81
82 /// The AWS region this client is configured for.
83 ///
84 /// Why: public-API compatibility passthrough (see [`Self::new`]) — exposed
85 /// for diagnostics and telemetry by any caller that held the pre-#2407 type.
86 /// What: delegates to the shared adapter's `region()`.
87 /// Test: `bedrock::tests::region_reports_resolved_value`.
88 pub fn region(&self) -> &str {
89 self.inner.region()
90 }
91
92 /// Execute one Converse call and return the response.
93 ///
94 /// Why: the single method `DispatchingLlmClient` needs to satisfy
95 /// `LlmClientTrait::chat` for `bedrock/*` slugs.
96 /// What: converts `req` to the shared request (the FULL slug is passed as the
97 /// wire model — the shared adapter strips the `bedrock/` prefix before the AWS
98 /// call), delegates to the shared [`BedrockAdapter`], maps a shared
99 /// [`trusty_common::inference::InferenceError`] to [`LlmError`], and converts
100 /// the shared response back to tcode's [`ChatResponse`].
101 /// Test: the shared adapter's conversion tests + the `#[ignore]`-gated live
102 /// call cover the wire behaviour end-to-end.
103 pub async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, LlmError> {
104 let shared = to_shared_request(req, req.model.clone());
105 let resp = self.inner.chat(&shared).await.map_err(map_error)?;
106 Ok(from_shared_response(resp))
107 }
108}
109
110// ── Tests ─────────────────────────────────────────────────────────────────────
111
112#[cfg(test)]
113mod tests {
114 use super::*;
115
116 /// `from_env` builds a client without touching AWS (the shared adapter's
117 /// client is lazy).
118 ///
119 /// Why: pins that constructing the Bedrock transport — e.g. on the first
120 /// `bedrock/*` dispatch — requires no AWS credentials, matching the
121 /// pre-migration lazy-construction guarantee (#2245).
122 /// What: call `from_env`; assert it succeeds.
123 /// Test: this test.
124 #[tokio::test]
125 async fn from_env_constructs_offline() {
126 assert!(BedrockChatClient::from_env().await.is_ok());
127 }
128
129 /// `new` with an explicit region builds a client without touching AWS.
130 ///
131 /// Why: pins the public-API-compatibility constructor's lazy-construction
132 /// guarantee, matching [`from_env_constructs_offline`].
133 /// What: call `new(Some("us-west-2"))`; assert it succeeds.
134 /// Test: this test.
135 #[tokio::test]
136 async fn new_constructs_offline() {
137 assert!(BedrockChatClient::new(Some("us-west-2")).await.is_ok());
138 }
139
140 /// `region()` reports the resolved region, explicit value preferred.
141 ///
142 /// Why: pins the public-API-compatibility accessor actually reflects what
143 /// the shared adapter resolved, not a stale/default value.
144 /// What: build with an explicit region; assert `region()` returns it.
145 /// Test: this test.
146 #[tokio::test]
147 async fn region_reports_resolved_value() {
148 let client = BedrockChatClient::new(Some("eu-west-1"))
149 .await
150 .expect("build");
151 assert_eq!(client.region(), "eu-west-1");
152 }
153}