Skip to main content

agentmux_srv/server/
model_gateway_bedrock.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The gateway's parts that are Bedrock's own (`docs/specs/SPEC_BEDROCK_MODEL_ROUTE_2026_12_01.md`): the answers the gateway
5//! gives itself, Bedrock's refusals as one sentence each, and the way to a model that does not speak Messages (Amazon Ergo):
6//! its request is translated to Chat Completions, sent with the bearer key, and its answer translated back, so the harness, the
7//! usage meter and the caps see Messages throughout. `model_gateway_handlers.rs` calls in from the one place a request is
8//! forwarded.
9
10use super::model_gateway_handlers::{gateway_client, refuse, relay_body, MAX_REQUEST};
11use super::*;
12use crate::backend::model_gateway::{bedrock, catalog, chat_adapter, token};
13use axum::body::{Body, Bytes};
14use axum::http::{header, HeaderMap, HeaderValue, StatusCode};
15use futures_util::Stream;
16use serde_json::Value;
17use std::pin::Pin;
18use std::task::{Context, Poll};
19
20/// The harness calls the gateway answers itself on this route: Bedrock's Messages path has no count call and no models list.
21pub(super) fn answered_here(tail: &str) -> bool {
22    matches!(tail, "v1/messages/count_tokens" | "v1/models")
23}
24
25/// The answer to one of [`answered_here`]: no key is read and nothing leaves the machine.
26pub(super) async fn answer_here(route: &'static catalog::Route, tail: &str, body: Body) -> Response {
27    if tail == "v1/models" {
28        return Json(bedrock::models_answer(route)).into_response();
29    }
30    match axum::body::to_bytes(body, MAX_REQUEST).await {
31        Ok(bytes) => Json(bedrock::count_tokens_answer(&bytes)).into_response(),
32        Err(_) => refuse(StatusCode::PAYLOAD_TOO_LARGE, "request_too_large", "the request is too large"),
33    }
34}
35
36/// The request with its model made one the route serves, and that model: the one the request names when the route serves it,
37/// else the agent's own. The wire and the price both follow it.
38pub(super) fn served(route: &'static catalog::Route, chosen: &'static catalog::Model, request: &[u8]) -> (Vec<u8>, &'static catalog::Model) {
39    let served = super::model_gateway_handlers::served_body(request, chosen.id, route);
40    let model = crate::backend::model_gateway::request::named_model(&served).and_then(|named| route.model(&named)).unwrap_or(chosen);
41    (served, model)
42}
43
44/// What Bedrock answered with when it did not serve the request.
45struct Failed {
46    status: StatusCode,
47    error_type: Option<String>,
48    retry_after: Option<HeaderValue>,
49    body: String,
50}
51
52async fn failed(response: reqwest::Response) -> Failed {
53    Failed {
54        status: response.status(),
55        error_type: response.headers().get("x-amzn-errortype").and_then(|v| v.to_str().ok()).map(str::to_string),
56        retry_after: response.headers().get(header::RETRY_AFTER).cloned(),
57        body: response.text().await.unwrap_or_default(),
58    }
59}
60
61/// The one sentence for a refusal [`bedrock::refusal`] names, in the shape the harness shows; a 429 keeps its retry hint, so the
62/// harness backs off. `None` for any other: its words are the caller's to pass on.
63fn named(failure: &Failed, model: &'static catalog::Model, profile: bedrock::Profile, region: &str) -> Option<Response> {
64    let profile_id = bedrock::profile_model(profile, model.id);
65    let said = bedrock::refusal(failure.status.as_u16(), failure.error_type.as_deref(), &failure.body, model.label, &profile_id, region)?;
66    tracing::warn!(
67        route = bedrock::ROUTE_ID, status = failure.status.as_u16(), error_type = failure.error_type.as_deref().unwrap_or(""),
68        "model gateway: Bedrock refused: {}", said.message
69    );
70    let mut answer = refuse(StatusCode::from_u16(said.status).unwrap_or(StatusCode::BAD_GATEWAY), said.kind, &said.message);
71    if let Some(after) = &failure.retry_after {
72        answer.headers_mut().insert(header::RETRY_AFTER, after.clone());
73    }
74    Some(answer)
75}
76
77/// Bedrock's answer when it served the request; when it did not, the sentence for a refusal that is named, and else Bedrock's own
78/// words in the status it gave.
79pub(super) async fn named_error(response: reqwest::Response, model: &'static catalog::Model, profile: bedrock::Profile, region: &str) -> Result<reqwest::Response, Response> {
80    if response.status().is_success() {
81        return Ok(response);
82    }
83    let failure = failed(response).await;
84    Err(named(&failure, model, profile, region).unwrap_or_else(|| {
85        let mut answer = (failure.status, failure.body).into_response();
86        answer.headers_mut().insert(header::CONTENT_TYPE, HeaderValue::from_static("application/json"));
87        answer
88    }))
89}
90
91/// What a Chat Completions error says, for the harness: the message in its error object, or the first of its words.
92fn message_of(body: &str) -> String {
93    let said = serde_json::from_str::<Value>(body).ok().and_then(|v| {
94        let message = |x: &Value| x.get("message").and_then(Value::as_str).map(str::to_string);
95        v.get("error").and_then(|e| message(e).or_else(|| e.as_str().map(str::to_string))).or_else(|| message(&v))
96    });
97    said.filter(|m| !m.trim().is_empty()).unwrap_or_else(|| body.trim().chars().take(300).collect())
98}
99
100/// A request to a model that speaks Chat Completions, for the harness that speaks Messages.
101pub(super) async fn forward(
102    grant: &token::Grant,
103    route: &'static catalog::Route,
104    model: &'static catalog::Model,
105    profile: bedrock::Profile,
106    region: &str,
107    key: &str,
108    request: &[u8],
109) -> Response {
110    let upstream_model = bedrock::profile_model(profile, model.id);
111    let chat = match chat_adapter::request_to_chat_with(request, &upstream_model, model.label, bedrock::chat_rules(model.id)) {
112        Ok(chat) => chat,
113        Err(e) => return refuse(StatusCode::BAD_REQUEST, "invalid_request_error", &e.to_string()),
114    };
115    let accept = if chat.stream { "text/event-stream" } else { "application/json" };
116    let sent = gateway_client()
117        .post(bedrock::chat_url(route, region))
118        .header(header::CONTENT_TYPE, "application/json")
119        .header(header::ACCEPT, accept)
120        .header(header::ACCEPT_ENCODING, "identity")
121        .bearer_auth(key)
122        .body(chat.body)
123        .send()
124        .await;
125    let response = match sent {
126        Ok(response) => response,
127        Err(e) => {
128            tracing::warn!(agent = %grant.agent, route = route.id, error = %e.without_url(), "model gateway: upstream unreachable");
129            return refuse(StatusCode::BAD_GATEWAY, "api_error", &format!("{} could not be reached", route.label));
130        }
131    };
132    if !response.status().is_success() {
133        let failure = failed(response).await;
134        return named(&failure, model, profile, region).unwrap_or_else(|| refuse(failure.status, "api_error", &message_of(&failure.body)));
135    }
136    let factor = bedrock::price_factor(profile, model);
137    if chat.stream {
138        streamed(response, grant, model, factor)
139    } else {
140        whole(response, grant, model, factor).await
141    }
142}
143
144/// The answer as a Messages stream, made as the upstream's arrives.
145fn streamed(response: reqwest::Response, grant: &token::Grant, model: &'static catalog::Model, price_factor: f64) -> Response {
146    let mut headers = HeaderMap::new();
147    headers.insert(header::CONTENT_TYPE, HeaderValue::from_static("text/event-stream"));
148    let inner = Translated { inner: Box::pin(response.bytes_stream()), translator: chat_adapter::StreamTranslator::new(model.id), ended: false };
149    relay_body(StatusCode::OK, headers, Box::pin(inner), true, grant, model, price_factor)
150}
151
152/// The answer as one Messages body, for a caller that did not ask for a stream.
153async fn whole(response: reqwest::Response, grant: &token::Grant, model: &'static catalog::Model, price_factor: f64) -> Response {
154    let Ok(bytes) = response.bytes().await else {
155        return refuse(StatusCode::BAD_GATEWAY, "api_error", "Bedrock's answer could not be read");
156    };
157    let body = chat_adapter::chat_json_to_message(&bytes, model.id);
158    let is_error = serde_json::from_slice::<Value>(&body).ok().and_then(|v| v.get("type").and_then(Value::as_str).map(|t| t == "error")).unwrap_or(false);
159    let mut headers = HeaderMap::new();
160    headers.insert(header::CONTENT_TYPE, HeaderValue::from_static("application/json"));
161    let status = if is_error { StatusCode::BAD_GATEWAY } else { StatusCode::OK };
162    let once = futures_util::stream::once(async move { Ok::<Bytes, reqwest::Error>(Bytes::from(body)) });
163    relay_body(status, headers, Box::pin(once), false, grant, model, price_factor)
164}
165
166/// The upstream's bytes, translated from Chat Completions events to Messages events as they pass. At the end of the upstream
167/// it says what the translator has left: the close of the message, or the error that the answer was cut off.
168struct Translated {
169    inner: Pin<Box<dyn Stream<Item = Result<Bytes, reqwest::Error>> + Send>>,
170    translator: chat_adapter::StreamTranslator,
171    ended: bool,
172}
173
174impl Stream for Translated {
175    type Item = Result<Bytes, reqwest::Error>;
176
177    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
178        loop {
179            if self.ended {
180                return Poll::Ready(None);
181            }
182            match self.inner.as_mut().poll_next(cx) {
183                Poll::Ready(Some(Ok(chunk))) => {
184                    let out = self.translator.push(&chunk);
185                    if !out.is_empty() {
186                        return Poll::Ready(Some(Ok(Bytes::from(out))));
187                    }
188                }
189                Poll::Ready(Some(Err(e))) => return Poll::Ready(Some(Err(e))),
190                Poll::Ready(None) => {
191                    self.ended = true;
192                    let out = self.translator.finish();
193                    return if out.is_empty() { Poll::Ready(None) } else { Poll::Ready(Some(Ok(Bytes::from(out)))) };
194                }
195                Poll::Pending => return Poll::Pending,
196            }
197        }
198    }
199}