Skip to main content

Response

Struct Response 

Source
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 allowsReply
application/json, or the header is absentapplication/json
otherwise text/plaintext/plain: a string value as it is, any other value as JSON text
otherwise application/octet-streamapplication/octet-stream: the bytes of the JSON text
none of theseapplication/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

Source

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.

Source

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.

Source

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.

Source

pub fn stream<S, T, E>(stream: S) -> Self
where S: Stream<Item = Result<T, E>> + Send + 'static, T: Serialize, E: Into<Box<dyn Error + Send + Sync>>,

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 Debug for Response

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl IntoInvocationResponse for Response

Source§

fn into_invocation_response(self) -> Response

Converts self into a response.
Source§

impl IntoResponse for Response

Source§

fn into_response(self) -> Response

Create a response.

Auto Trait Implementations§

§

impl !RefUnwindSafe for Response

§

impl !Sync for Response

§

impl !UnwindSafe for Response

§

impl Forget for Response

§

impl Freeze for Response
where 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
where NonZero<u16>: Send, RawVecInner: Send, BoxRaw<ErrorImpl>: Send, BoxRaw<Response<Body>>: Send, BoxRaw<dyn Stream<Item = Result<Event, !>> + Send>: Send, Arc<(OnceLock<Failure>, Atomic<bool>)>: Send,

§

impl Unpin for Response
where NonZero<u16>: Unpin, *const u8 is !null: Unpin, Box<ErrorImpl>: Unpin, Box<Response<Body>>: Unpin, Box<dyn Stream<Item = Result<Event, !>> + Send>: Unpin, Arc<(OnceLock<Failure>, Atomic<bool>)>: Unpin,

§

impl UnsafeUnpin for Response
where 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> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts 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
Source§

impl<Unshared, Shared> IntoShared<Shared> for Unshared
where Shared: FromUnshared<Unshared>,

Source§

fn into_shared(self) -> Shared

Creates a shared type from an unshared type.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more