Skip to content

invoke_code_interpreter async

invoke_code_interpreter(
    code_interpreter_identifier: str,
    name: ToolName,
    *,
    config_overrides: Optional[AsyncBedrockAgentCoreClientConfig] = None,
    session_id: Optional[CodeInterpreterSessionId] = None,
    trace_id: Optional[str] = None,
    trace_parent: Optional[str] = None,
    arguments: Optional[ToolArguments] = None,
) -> AsyncGenerator[InvokeCodeInterpreterResponse]

Executes code within an active code interpreter session in Amazon Bedrock AgentCore. This operation processes the provided code, runs it in a secure environment, and returns the execution results including output, errors, and generated visualizations.

To execute code, you must specify the code interpreter identifier, session ID, and the code to run in the arguments parameter. The operation returns a stream containing the execution results, which can include text output, error messages, and data visualizations.

This operation is subject to request rate limiting based on your account's service quotas.

The following operations are related to InvokeCodeInterpreter:

Parameters:

  • code_interpreter_identifier (str) –

    The unique identifier of the code interpreter associated with the session. This must match the identifier used when creating the session with StartCodeInterpreterSession.

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

    The unique identifier of the code interpreter session to use. This must be an active session created with StartCodeInterpreterSession. If the session has expired or been stopped, the request will fail.

  • trace_id (Optional[str], default: None ) –

    The trace identifier for request tracking.

  • trace_parent (Optional[str], default: None ) –

    The parent trace information for distributed tracing.

  • name (ToolName) –

    The name of the code interpreter to invoke.

  • arguments (Optional[ToolArguments], default: None ) –

    The arguments for the code interpreter. This includes the code to execute and any additional parameters such as the programming language, whether to clear the execution context, and other execution options. The structure of this parameter depends on the specific code interpreter being used.

Raises:

  • AccessDeniedException –

    The exception that occurs when you do not have sufficient permissions to perform an action. Verify that your IAM policy includes the necessary permissions for the operation you are trying to perform.

  • ConflictException –

    The exception that occurs when the request conflicts with the current state of the resource. This can happen when trying to modify a resource that is currently being modified by another request, or when trying to create a resource that already exists.

  • InternalServerException –

    The exception that occurs when the service encounters an unexpected internal error. This is a temporary condition that will resolve itself with retries. We recommend implementing exponential backoff retry logic in your application.

  • ResourceNotFoundException –

    The exception that occurs when the specified resource does not exist. This can happen when using an invalid identifier or when trying to access a resource that has been deleted.

  • ServiceQuotaExceededException –

    The exception that occurs when the request would cause a service quota to be exceeded. Review your service quotas and either reduce your request rate or request a quota increase.

  • ThrottlingException –

    The exception that occurs when the request was denied due to request throttling. This happens when you exceed the allowed request rate for an operation. Reduce the frequency of requests or implement exponential backoff retry logic in your application.

  • ValidationException –

    The exception that occurs when the input fails to satisfy the constraints specified by the service. Check the error message for details about which input parameter is invalid and correct your request.

  • UnknownServiceError –

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

Source code in docs_src/capo_bedrock_agentcore/_services/async_bedrock_agent_core.py
@asynccontextmanager
async def invoke_code_interpreter(
    self,
    code_interpreter_identifier: str,
    name: "capo_bedrock_agentcore.types.tool_name.ToolName",
    *,
    config_overrides: Optional[AsyncBedrockAgentCoreClientConfig] = None,
    session_id: Optional[
        "capo_bedrock_agentcore.types.code_interpreter_session_id.CodeInterpreterSessionId"
    ] = None,
    trace_id: Optional[str] = None,
    trace_parent: Optional[str] = None,
    arguments: Optional[
        "capo_bedrock_agentcore.types.tool_arguments.ToolArguments"
    ] = None,
) -> "AsyncGenerator[capo_bedrock_agentcore.types.invoke_code_interpreter_response.InvokeCodeInterpreterResponse]":
    """<p>Executes code within an active code interpreter session in Amazon Bedrock AgentCore. This operation processes the provided code, runs it in a secure environment, and returns the execution results including output, errors, and generated visualizations.</p> <p>To execute code, you must specify the code interpreter identifier, session ID, and the code to run in the arguments parameter. The operation returns a stream containing the execution results, which can include text output, error messages, and data visualizations.</p> <p>This operation is subject to request rate limiting based on your account's service quotas.</p> <p>The following operations are related to <code>InvokeCodeInterpreter</code>:</p> <ul> <li> <p> <a href="https://docs.aws.amazon.com/bedrock-agentcore/latest/APIReference/API_StartCodeInterpreterSession.html">StartCodeInterpreterSession</a> </p> </li> <li> <p> <a href="https://docs.aws.amazon.com/bedrock-agentcore/latest/APIReference/API_GetCodeInterpreterSession.html">GetCodeInterpreterSession</a> </p> </li> </ul>

    Args:
        code_interpreter_identifier: <p>The unique identifier of the code interpreter associated with the session. This must match the identifier used when creating the session with <code>StartCodeInterpreterSession</code>.</p>
        session_id: <p>The unique identifier of the code interpreter session to use. This must be an active session created with <code>StartCodeInterpreterSession</code>. If the session has expired or been stopped, the request will fail.</p>
        trace_id: <p>The trace identifier for request tracking.</p>
        trace_parent: <p>The parent trace information for distributed tracing.</p>
        name: <p>The name of the code interpreter to invoke.</p>
        arguments: <p>The arguments for the code interpreter. This includes the code to execute and any additional parameters such as the programming language, whether to clear the execution context, and other execution options. The structure of this parameter depends on the specific code interpreter being used.</p>

    Raises:
        capo_bedrock_agentcore.errors.access_denied_exception.AccessDeniedException: <p>The exception that occurs when you do not have sufficient permissions to perform an action. Verify that your IAM policy includes the necessary permissions for the operation you are trying to perform.</p>
        capo_bedrock_agentcore.errors.conflict_exception.ConflictException: <p>The exception that occurs when the request conflicts with the current state of the resource. This can happen when trying to modify a resource that is currently being modified by another request, or when trying to create a resource that already exists.</p>
        capo_bedrock_agentcore.errors.internal_server_exception.InternalServerException: <p>The exception that occurs when the service encounters an unexpected internal error. This is a temporary condition that will resolve itself with retries. We recommend implementing exponential backoff retry logic in your application.</p>
        capo_bedrock_agentcore.errors.resource_not_found_exception.ResourceNotFoundException: <p>The exception that occurs when the specified resource does not exist. This can happen when using an invalid identifier or when trying to access a resource that has been deleted.</p>
        capo_bedrock_agentcore.errors.service_quota_exceeded_exception.ServiceQuotaExceededException: <p>The exception that occurs when the request would cause a service quota to be exceeded. Review your service quotas and either reduce your request rate or request a quota increase.</p>
        capo_bedrock_agentcore.errors.throttling_exception.ThrottlingException: <p>The exception that occurs when the request was denied due to request throttling. This happens when you exceed the allowed request rate for an operation. Reduce the frequency of requests or implement exponential backoff retry logic in your application.</p>
        capo_bedrock_agentcore.errors.validation_exception.ValidationException: <p>The exception that occurs when the input fails to satisfy the constraints specified by the service. Check the error message for details about which input parameter is invalid and correct your request.</p>
        capo_bedrock_agentcore.errors.UnknownServiceError: The service returned an error code this client does not model.
    """

    async def _handler(
        req: "AsyncOperationRequest[capo_bedrock_agentcore.types.invoke_code_interpreter_request.InvokeCodeInterpreterRequest]",
    ) -> AsyncOperationResponse[
        "capo_bedrock_agentcore.types.invoke_code_interpreter_response.InvokeCodeInterpreterResponse"
    ]:
        import capo_bedrock_agentcore._operations.amazon_bedrock_agent_core.invoke_code_interpreter

        (
            output,
            http_response,
        ) = await capo_bedrock_agentcore._operations.amazon_bedrock_agent_core.invoke_code_interpreter.async_invoke_code_interpreter(
            req.options, req.input
        )
        return AsyncOperationResponse(output=output, response=http_response)

    def _redact_input(
        input_: "capo_bedrock_agentcore.types.invoke_code_interpreter_request.InvokeCodeInterpreterRequest",
    ) -> dict[str, Any]:
        import capo_bedrock_agentcore.types.invoke_code_interpreter_request

        return capo_bedrock_agentcore.types.invoke_code_interpreter_request.redact_sensitive(
            input_
        )

    def _redact_output(
        output: "capo_bedrock_agentcore.types.invoke_code_interpreter_response.InvokeCodeInterpreterResponse",
    ) -> dict[str, Any]:
        import capo_bedrock_agentcore.types.invoke_code_interpreter_response

        return capo_bedrock_agentcore.types.invoke_code_interpreter_response.redact_sensitive(
            output
        )

    interceptors_, options_ = self.operation_options(
        config_overrides,
        OperationLogging(
            "InvokeCodeInterpreter",
            redact_input=_redact_input,
            redact_output=_redact_output,
        ),
    )
    input_: capo_bedrock_agentcore.types.invoke_code_interpreter_request.InvokeCodeInterpreterRequest = {
        "code_interpreter_identifier": code_interpreter_identifier,
        "name": name,
    }
    if session_id is not None:
        input_["session_id"] = session_id
    if trace_id is not None:
        input_["trace_id"] = trace_id
    if trace_parent is not None:
        input_["trace_parent"] = trace_parent
    if arguments is not None:
        input_["arguments"] = arguments

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