Skip to main content

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 wrapper that delegates every method
10//! to the shared adapter — zero local Bedrock/Converse logic.
11//! What: [`BedrockChatClient`] wraps a
12//! [`trusty_common::inference::BedrockAdapter`] and implements
13//! [`InferenceAdapter`] by delegation. Since #4425 unified trusty-code's wire
14//! types with `trusty_common::inference`'s, the wrapper no longer converts
15//! anything: the request, the response, and the error type are already the
16//! shared ones, so the former `super::convert` bridge is gone. The shared
17//! adapter constructs its AWS client lazily on first `chat`, so
18//! [`Self::from_env`]/[`Self::new`] touch no AWS credentials.
19//! [`Self::new`]/[`Self::region`] are thin passthroughs kept for public-API
20//! compatibility with the pre-#2407 local transport (no in-tree caller uses
21//! them post-migration, but this is a published rlib crate and the surface
22//! removal would otherwise be undocumented/silent).
23//!
24//! Streaming (#4425/#4426): [`Self::chat_stream`] forwards to the shared
25//! adapter's, which since #4426 is a NATIVE `ConverseStream` transport — a
26//! Bedrock turn arrives token-by-token, not as one buffered delta. This
27//! wrapper needed no edit for that (only this doc line): because it delegates
28//! rather than reimplements, the whole change landed inside
29//! `trusty_common::inference::bedrock`.
30//! Test: `bedrock::tests::*` (offline construction) plus the shared adapter's own
31//! conversion + `#[ignore]`-gated live coverage in
32//! `trusty_common::inference::bedrock`.
33
34use async_trait::async_trait;
35use trusty_common::inference::{
36    BedrockAdapter, ChatRequest, ChatResponse, ChatStream, InferenceAdapter, InferenceError,
37    ProviderCapabilities, ToolChoice,
38};
39
40/// AWS Bedrock Converse transport, backed by the shared inference adapter.
41///
42/// Why: satisfies the same `chat(&ChatRequest) -> Result<ChatResponse, ..>`
43/// contract every other tcode transport exposes, so `DispatchingLlmClient`
44/// (`super::dispatch`) can route `bedrock/*` slugs here without any caller
45/// knowing the backend differs — while the Converse mechanics live in
46/// `trusty_common::inference::bedrock`, not in this crate.
47/// What: holds a shared [`BedrockAdapter`] (which owns the resolved region and a
48/// lazily-built AWS client). `Debug` so `DispatchingLlmClient`'s
49/// `OnceCell<BedrockChatClient>` can derive it.
50/// Test: `bedrock::tests::from_env_constructs_offline`.
51#[derive(Debug)]
52pub struct BedrockChatClient {
53    inner: BedrockAdapter,
54}
55
56impl BedrockChatClient {
57    /// Construct a `BedrockChatClient` for an explicit (or default) region.
58    ///
59    /// Why: public-API compatibility passthrough — the pre-#2407 local transport
60    /// exposed this constructor; no in-tree caller uses it today (everything goes
61    /// through [`Self::from_env`] via `DispatchingLlmClient`), but this is a
62    /// published rlib crate, so the constructor is kept rather than silently
63    /// dropped.
64    /// What: wraps [`BedrockAdapter::new`] with `region`. Async + `Result` to
65    /// match the pre-migration signature; never actually fails.
66    /// Test: `bedrock::tests::new_constructs_offline`.
67    pub async fn new(region: Option<&str>) -> Result<Self, InferenceError> {
68        Ok(Self {
69            inner: BedrockAdapter::new(region),
70        })
71    }
72
73    /// Construct a `BedrockChatClient` from the environment.
74    ///
75    /// Why: the convenience entry point `DispatchingLlmClient` lazily calls on
76    /// the first `bedrock/*` request. Region resolves from
77    /// `TRUSTY_AWS_REGION`/`AWS_REGION`/default; credentials come from the AWS
78    /// chain, resolved lazily on the first `chat`, so this never touches AWS.
79    /// What: delegates to [`Self::new`] with `region: None`.
80    /// Test: `bedrock::tests::from_env_constructs_offline`.
81    pub async fn from_env() -> Result<Self, InferenceError> {
82        Self::new(None).await
83    }
84
85    /// The AWS region this client is configured for.
86    ///
87    /// Why: public-API compatibility passthrough (see [`Self::new`]) — exposed
88    /// for diagnostics and telemetry by any caller that held the pre-#2407 type.
89    /// What: delegates to the shared adapter's `region()`.
90    /// Test: `bedrock::tests::region_reports_resolved_value`.
91    pub fn region(&self) -> &str {
92        self.inner.region()
93    }
94}
95
96/// Delegating [`InferenceAdapter`] impl (#4425).
97///
98/// Why: `DispatchingLlmClient` routes `bedrock/*` slugs here through the SHARED
99/// trait, so this wrapper must satisfy that trait rather than expose a
100/// look-alike inherent `chat`. Every method delegates — including the
101/// capability and tool-choice hooks, which Bedrock overrides with the
102/// Anthropic dialect: forwarding them (instead of inheriting the trait's
103/// OpenAI-dialect defaults) is what keeps a `bedrock/*` turn wire-identical to
104/// calling the shared adapter directly.
105/// What: name/capabilities/chat/chat_stream/map_tool_choice all forward to
106/// [`BedrockAdapter`]. The capability-derived `supports_*` defaults need no
107/// override because they read `capabilities()`, which is forwarded.
108/// Test: `bedrock::tests::*`; wire behaviour is covered by the shared adapter's
109/// own tests.
110#[async_trait]
111impl InferenceAdapter for BedrockChatClient {
112    fn name(&self) -> &str {
113        self.inner.name()
114    }
115
116    fn capabilities(&self) -> &ProviderCapabilities {
117        self.inner.capabilities()
118    }
119
120    // #4425: forward the model-aware form too — a decorator that answered it
121    // from the trait default would silently drop back to `capabilities()` and
122    // stop reflecting the wrapped adapter.
123    fn capabilities_for(&self, model: &str) -> &ProviderCapabilities {
124        self.inner.capabilities_for(model)
125    }
126
127    async fn chat(&self, request: &ChatRequest) -> Result<ChatResponse, InferenceError> {
128        self.inner.chat(request).await
129    }
130
131    async fn chat_stream(&self, request: &ChatRequest) -> Result<ChatStream, InferenceError> {
132        self.inner.chat_stream(request).await
133    }
134
135    fn map_tool_choice(&self, choice: ToolChoice) -> serde_json::Value {
136        self.inner.map_tool_choice(choice)
137    }
138}
139
140// ── Tests ─────────────────────────────────────────────────────────────────────
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145
146    /// `from_env` builds a client without touching AWS (the shared adapter's
147    /// client is lazy).
148    ///
149    /// Why: pins that constructing the Bedrock transport — e.g. on the first
150    /// `bedrock/*` dispatch — requires no AWS credentials, matching the
151    /// pre-migration lazy-construction guarantee (#2245).
152    /// What: call `from_env`; assert it succeeds.
153    /// Test: this test.
154    #[tokio::test]
155    async fn from_env_constructs_offline() {
156        assert!(BedrockChatClient::from_env().await.is_ok());
157    }
158
159    /// `new` with an explicit region builds a client without touching AWS.
160    ///
161    /// Why: pins the public-API-compatibility constructor's lazy-construction
162    /// guarantee, matching [`from_env_constructs_offline`].
163    /// What: call `new(Some("us-west-2"))`; assert it succeeds.
164    /// Test: this test.
165    #[tokio::test]
166    async fn new_constructs_offline() {
167        assert!(BedrockChatClient::new(Some("us-west-2")).await.is_ok());
168    }
169
170    /// `region()` reports the resolved region, explicit value preferred.
171    ///
172    /// Why: pins the public-API-compatibility accessor actually reflects what
173    /// the shared adapter resolved, not a stale/default value.
174    /// What: build with an explicit region; assert `region()` returns it.
175    /// Test: this test.
176    #[tokio::test]
177    async fn region_reports_resolved_value() {
178        let client = BedrockChatClient::new(Some("eu-west-1"))
179            .await
180            .expect("build");
181        assert_eq!(client.region(), "eu-west-1");
182    }
183}