Skip to content

agentic_retrieve_stream async

agentic_retrieve_stream(
    agent_context_id: AgentContextIdentifier,
    messages: MessageList,
    *,
    config_overrides: Optional[AsyncContextClientConfig] = None,
    session_id: Optional[SessionId] = None,
    analysis_configuration: Optional[AnalysisConfiguration] = None,
    retrieval_configuration: Optional[StreamRetrievalConfiguration] = None,
) -> AsyncGenerator[AgenticRetrieveStreamResponse]

Answers a natural-language question against an agent context and streams the work as it happens. The response is an event stream that contains progress events while AWS Context searches the agent context, the answer in chunks as it is generated, and a final result. The final result contains the answer and the ranked retrieved context.

Parameters:

  • agent_context_id (AgentContextIdentifier) –

    The agent context to retrieve from, by its ID or ARN.

  • messages (MessageList) –

    The conversation, as an ordered list of turns. A single-question caller sends one user message. The list carries multi-turn history so a follow-up resolves against earlier turns.

  • session_id (Optional[SessionId], default: None ) –

    Optional. A key that you supply to group related calls, for example the turns of one conversation, for trace storage and analysis. Grouping is per account, across agent contexts, so use a value that is unique to each conversation.

  • analysis_configuration (Optional[AnalysisConfiguration], default: None ) –

    Optional controls for post-call analysis of the retrieval: whether its trace is stored for analysis. Trace events are streamed either way.

  • retrieval_configuration (Optional[StreamRetrievalConfiguration], default: None ) –

    Optional bounds and configuration for the agent loop.

Raises:

  • AccessDeniedException –

    You don't have sufficient access to perform this operation. Verify that you have permission to perform the operation on the resource.

  • InternalServerException –

    The request failed because of an internal error. Retry the request.

  • ThrottlingException –

    The request was denied because it exceeded a request rate quota. Wait, then retry the request.

  • ValidationException –

    The input fails to satisfy the constraints of the operation. Correct the input before you retry the request.

  • ConflictException –

    The request conflicts with the current state of the resource. Check the resource's current state before you retry the request.

  • ResourceNotFoundException –

    The specified resource was not found. Check that the ID is correct and that the resource exists in your account and Region.

  • UnknownServiceError –

    The service returned an error code this client does not model.

Examples:

Ask a question about an agent context The following example asks which table holds customer orders. The response is an event stream; this example shows only its final result event, which carries the answer, the retrieved context, and a citation.

>>> await client.agentic_retrieve_stream(agent_context_id='ac-0123456789abcdef0123456789abcdef', session_id='sales-analytics-chat-0001', messages=[{'role': 'USER', 'content': 'Which table holds customer order data?'}], retrieval_configuration={'maxIterations': 10})
Source code in docs_src/capo_context/_services/async_context.py
@asynccontextmanager
async def agentic_retrieve_stream(
    self,
    agent_context_id: "capo_context.types.agent_context_identifier.AgentContextIdentifier",
    messages: "capo_context.types.message_list.MessageList",
    *,
    config_overrides: Optional[AsyncContextClientConfig] = None,
    session_id: Optional["capo_context.types.session_id.SessionId"] = None,
    analysis_configuration: Optional[
        "capo_context.types.analysis_configuration.AnalysisConfiguration"
    ] = None,
    retrieval_configuration: Optional[
        "capo_context.types.stream_retrieval_configuration.StreamRetrievalConfiguration"
    ] = None,
) -> "AsyncGenerator[capo_context.types.agentic_retrieve_stream_response.AgenticRetrieveStreamResponse]":
    """<p>Answers a natural-language question against an agent context and streams the work as it happens. The response is an event stream that contains progress events while AWS Context searches the agent context, the answer in chunks as it is generated, and a final result. The final result contains the answer and the ranked retrieved context.</p>

    Args:
        agent_context_id: <p>The agent context to retrieve from, by its ID or ARN.</p>
        messages: <p>The conversation, as an ordered list of turns. A single-question caller sends one user message. The list carries multi-turn history so a follow-up resolves against earlier turns.</p>
        session_id: <p>Optional. A key that you supply to group related calls, for example the turns of one conversation, for trace storage and analysis. Grouping is per account, across agent contexts, so use a value that is unique to each conversation.</p>
        analysis_configuration: <p>Optional controls for post-call analysis of the retrieval: whether its trace is stored for analysis. Trace events are streamed either way.</p>
        retrieval_configuration: <p>Optional bounds and configuration for the agent loop.</p>

    Raises:
        capo_context.errors.access_denied_exception.AccessDeniedException: <p>You don't have sufficient access to perform this operation. Verify that you have permission to perform the operation on the resource.</p>
        capo_context.errors.internal_server_exception.InternalServerException: <p>The request failed because of an internal error. Retry the request.</p>
        capo_context.errors.throttling_exception.ThrottlingException: <p>The request was denied because it exceeded a request rate quota. Wait, then retry the request.</p>
        capo_context.errors.validation_exception.ValidationException: <p>The input fails to satisfy the constraints of the operation. Correct the input before you retry the request.</p>
        capo_context.errors.conflict_exception.ConflictException: <p>The request conflicts with the current state of the resource. Check the resource's current state before you retry the request.</p>
        capo_context.errors.resource_not_found_exception.ResourceNotFoundException: <p>The specified resource was not found. Check that the ID is correct and that the resource exists in your account and Region.</p>
        capo_context.errors.UnknownServiceError: The service returned an error code this client does not model.

    Examples:
        Ask a question about an agent context
        The following example asks which table holds customer orders. The response is an event stream; this example shows only its final result event, which carries the answer, the retrieved context, and a citation.

        >>> await client.agentic_retrieve_stream(agent_context_id='ac-0123456789abcdef0123456789abcdef', session_id='sales-analytics-chat-0001', messages=[{'role': 'USER', 'content': 'Which table holds customer order data?'}], retrieval_configuration={'maxIterations': 10})
    """

    async def _handler(
        req: "AsyncOperationRequest[capo_context.types.agentic_retrieve_stream_request.AgenticRetrieveStreamRequest]",
    ) -> AsyncOperationResponse[
        "capo_context.types.agentic_retrieve_stream_response.AgenticRetrieveStreamResponse"
    ]:
        import capo_context._operations.context.agentic_retrieve_stream

        (
            output,
            http_response,
        ) = await capo_context._operations.context.agentic_retrieve_stream.async_agentic_retrieve_stream(
            req.options, req.input
        )
        awatch_event_stream(output, "stream", req.options)
        return AsyncOperationResponse(output=output, response=http_response)

    def _redact_input(
        input_: "capo_context.types.agentic_retrieve_stream_request.AgenticRetrieveStreamRequest",
    ) -> dict[str, Any]:
        import capo_context.types.agentic_retrieve_stream_request

        return capo_context.types.agentic_retrieve_stream_request.redact_sensitive(
            input_
        )

    def _redact_output(
        output: "capo_context.types.agentic_retrieve_stream_response.AgenticRetrieveStreamResponse",
    ) -> dict[str, Any]:
        import capo_context.types.agentic_retrieve_stream_response

        return capo_context.types.agentic_retrieve_stream_response.redact_sensitive(
            output
        )

    interceptors_, options_ = self.operation_options(
        config_overrides,
        OperationLogging(
            "AgenticRetrieveStream",
            redact_input=_redact_input,
            redact_output=_redact_output,
        ),
    )
    input_: capo_context.types.agentic_retrieve_stream_request.AgenticRetrieveStreamRequest = {
        "agent_context_id": agent_context_id,
        "messages": messages,
    }
    if session_id is not None:
        input_["session_id"] = session_id
    if analysis_configuration is not None:
        input_["analysis_configuration"] = analysis_configuration
    if retrieval_configuration is not None:
        input_["retrieval_configuration"] = retrieval_configuration

    response = await aexecute_pipeline(
        AsyncOperationRequest(input=input_, options=options_),
        handler=_handler,
        interceptors=list(interceptors_),
    )
    try:
        yield response.output
    finally:
        await response.response.aclose()