pub struct Response { /* private fields */ }Expand description
The reply of an invocation handler.
A handler can also return any Serialize value directly, which is the same as
Response::json. Use Response to set the status, to send a raw HTTP response,
or when one handler has to choose between several kinds of reply.
§Encoding
A value from json or with_status is encoded
by the Accept header of the request:
Accept allows | Reply |
|---|---|
application/json, or the header is absent | application/json |
otherwise text/plain | text/plain: a string value as it is, any other value as JSON text |
otherwise application/octet-stream | application/octet-stream: the bytes of the JSON text |
| none of these | application/json |
A type is allowed by its own media range, by a wildcard for its kind such as
application/*, or by */*. The most specific of these decides, and a range with
q=0 refuses the type: application/json;q=0, */* does not allow JSON. Other q
values and parameters have no effect. Media types match without regard to case,
and several Accept fields count as one list.
§Streaming
stream sends Server-Sent Events. A request with no Accept header
gets the stream, as the Python SDK sends it. A request whose Accept header does
not allow text/event-stream, by the rules above, receives 406. The server
decides this after the handler has returned the stream and before it reads the
stream. See stream for the event format and the error rules.
§Status codes behind AgentCore Runtime
A direct HTTP caller receives the status and body that the agent sends. A caller of
the InvokeAgentRuntime API does not: the service documents that it reports a
4xx or 5xx reply of the agent as a RuntimeClientError with HTTP status 424.
In tests against the service, a 201 reply was reported the same way. Use status
200 for a reply that the API caller must receive, and put the outcome in the body.
Response also implements axum’s IntoResponse. Returned from a route that is
not the invocation route, a value is always encoded as JSON and a stream is always
sent. The stream uses the heartbeat of the app on a route given to
Builder::routes, and the default of 30 seconds on any
other route.
Implementations§
Source§impl Response
impl Response
Sourcepub fn json<T: Serialize>(value: T) -> Self
pub fn json<T: Serialize>(value: T) -> Self
A 200 reply holding value.
If value fails to serialize, the client receives a 500 JSON error.
Sourcepub fn with_status<T: Serialize>(status: StatusCode, value: T) -> Self
pub fn with_status<T: Serialize>(status: StatusCode, value: T) -> Self
A reply with the given status holding value.
If value fails to serialize, the client receives a 500 JSON error. HTTP
allows no body for a 1xx, 204 or 304 status, so the server sends such a
reply without value.
Sourcepub fn from_http(response: Response<Body>) -> Self
pub fn from_http(response: Response<Body>) -> Self
A raw HTTP response. The server sends its status, headers and body unchanged
and does not look at the Accept header.
The body can be a stream. The request context stays available through
context::current while the server reads it.
When the body fails or panics, the server logs the cause and closes the
connection. A direct caller sees a reply that was cut. In tests against
AgentCore Runtime, the caller of InvokeAgentRuntime received such a reply
as a complete one. Send a last item that the caller checks when it must know
that the reply is complete.
Sourcepub fn stream<S, T, E>(stream: S) -> Self
pub fn stream<S, T, E>(stream: S) -> Self
A stream of Server-Sent Events. Each item is sent as soon as the stream yields it, as one event whose data is the JSON encoding of the item:
data: {"text":"hello"}The stream runs after the handler has returned, so it must own what it uses.
The request context stays available through
context::current while the stream runs.
§Do the work inside the stream
The server sends nothing while the handler runs, not even the status, and it
checks the Accept header only when the handler has returned. A handler
should therefore return the stream at once and do its work as the first step
of the stream. The work then starts no earlier than the reply, the heartbeat
covers it, and a request that gets 406 starts none of it:
use std::convert::Infallible;
use bedrock_agentcore::runtime::Response;
use futures_util::{StreamExt, stream};
async fn handler(prompt: String) -> Result<Response, Infallible> {
let reply = stream::once(async move {
let words = slow_lookup(prompt).await;
stream::iter(words.into_iter().map(Ok::<_, Infallible>))
})
.flatten();
Ok(Response::stream(reply))
}A handler that must decide before it starts work can read the Accept header
from RequestContext::request_headers.
When the connection to the agent closes, the server drops the stream. Behind
AgentCore Runtime that connection belongs to the service, not to the caller of
InvokeAgentRuntime. In tests against the service, a caller that disconnected
did not close it: the service read the stream to its end. Do not rely on a
caller’s disconnect to stop work in a deployed agent.
§Errors in the stream
The response status is already 200 when the stream starts. An Err item ends
the stream with one last event, and the server logs the invocation as failed:
event: error
data: {"error":"<Display text of the error>"}An item that fails to serialize ends it the same way with the text
Failed to serialize response. So does an unwinding panic in the stream, in the
serializer of an item, in the conversion of an error or in the destructors of a
stream that has ended, with the text Internal error. The log line of the
failure names the cause in each case.
To reply with a JSON 500 instead, return Err from the handler before it
creates the stream.
§Quiet streams
While the stream yields nothing, the server sends an SSE comment line every 30
seconds so that proxies keep the connection open. Change the interval with
Builder::stream_heartbeat. Clients ignore
comment lines.
Trait Implementations§
Source§impl IntoInvocationResponse for Response
impl IntoInvocationResponse for Response
Source§fn into_invocation_response(self) -> Response
fn into_invocation_response(self) -> Response
self into a response.Source§impl IntoResponse for Response
impl IntoResponse for Response
Source§fn into_response(self) -> Response
fn into_response(self) -> Response
Auto Trait Implementations§
impl !RefUnwindSafe for Response
impl !Sync for Response
impl !UnwindSafe for Response
impl Forget for Response
impl Freeze for Responsewhere
NonZero<u16>: Freeze,
*const u8 is !null: Freeze,
PhantomData<u8>: Freeze,
*const ErrorImpl is !null: Freeze,
PhantomData<ErrorImpl>: Freeze,
*const Response<Body> is !null: Freeze,
PhantomData<Response<Body>>: Freeze,
*const dyn Stream<Item = Result<Event, !>> + Send is !null: Freeze,
PhantomData<dyn Stream<Item = Result<Event, !>> + Send>: Freeze,
*const ArcInner<(OnceLock<Failure>, Atomic<bool>)> is !null: Freeze,
PhantomData<ArcInner<(OnceLock<Failure>, Atomic<bool>)>>: Freeze,
impl Move for Response
impl Send for Response
impl Unpin for Response
impl UnsafeUnpin for Responsewhere
NonZeroU16Inner: UnsafeUnpin,
*const u8 is !null: UnsafeUnpin,
PhantomData<u8>: UnsafeUnpin,
*const ErrorImpl is !null: UnsafeUnpin,
PhantomData<ErrorImpl>: UnsafeUnpin,
*const Response<Body> is !null: UnsafeUnpin,
PhantomData<Response<Body>>: UnsafeUnpin,
*const dyn Stream<Item = Result<Event, !>> + Send is !null: UnsafeUnpin,
PhantomData<dyn Stream<Item = Result<Event, !>> + Send>: UnsafeUnpin,
*const ArcInner<(OnceLock<Failure>, Atomic<bool>)> is !null: UnsafeUnpin,
PhantomData<ArcInner<(OnceLock<Failure>, Atomic<bool>)>>: UnsafeUnpin,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more