Skip to content

put_trace

put_trace(
    format: TraceFormat,
    trace_documents: TraceDocumentList,
    agent_context_arns: AgentContextOnlyArnList,
    *,
    config_overrides: Optional[ContextClientConfig] = None,
    session_id: Optional[SessionId] = None,
    client_token: Optional[ClientToken] = None,
    trace_metadata: Optional[TraceMetadata] = None,
    access_control_config: Optional[AccessControlConfig] = None,
) -> PutTraceResponse

Submits an agent's execution traces so that AWS Context can extract reusable knowledge and skills from them. Call it when an agent finishes a task or session that is worth learning from. In agentContextArns, name the agent contexts that the traces are about. AWS Context analyzes the traces for each of them.

Each traceDocuments entry is one raw trace document in the trace schema that format selects. You can send 1–100 documents per call. Each document can be up to 5 MiB before encoding. If you use an AWS SDK, pass each document's raw bytes. If you call PutTrace through the agent context's MCP server or another JSON client, send each document as a base64-encoded string. To send a larger trace, split it across calls that share a sessionId.

sessionId groups related calls into one session. If you omit it, AWS Context generates one and returns it in the response so that you can reuse it.

Each agent context can hold up to 100,000 trace documents. If a request would exceed this quota, it fails with ServiceQuotaExceededException, and AWS Context stores no documents. If a request fails for any other reason, AWS Context might have stored some of its documents. To store the rest without duplicates, retry with the same clientToken.

Parameters:

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

    The agent session this trace belongs to and the grouping key: multiple PutTrace calls with the same sessionId are one session. Optional. If you omit it, the service generates one and returns it in the response. It is not the traceId: an OTLP batch carries many trace_ids under one session.

  • client_token (Optional[ClientToken], default: None ) –

    Makes the call idempotent. A retry with the same token and the same request returns the same sessionId and does not write the traces again. Reusing the token fails with ValidationException if the request is different, or if another caller reuses it when accessControlConfig names no entries. A token is honored for 8 hours after its first use. When accessControlConfig names no entries and the caller's end user cannot be resolved at the time of the retry, the retry fails with ValidationException even if the first attempt stored traces. To complete them, resend with explicit entries under a new token.

  • format (TraceFormat) –

    The format of the documents in traceDocuments. Valid values:

    • OTEL - OpenTelemetry traces in OTLP/JSON.

    • ANTHROPIC - Claude Code session logs, one log line per document.

    • BEDROCK_CONVERSE - Amazon Bedrock Converse messages, one message (role and content) per document, in conversation order.

    • KIRO - Kiro IDE or Kiro CLI session logs.

  • trace_documents (TraceDocumentList) –

    The raw trace documents, in the trace schema that format selects. You can send 1–100 documents per call, and each document can be up to 5 MiB (5,242,880 bytes) before encoding. If you use an AWS SDK, pass each document's raw bytes. If you call PutTrace through the agent context's MCP server or another JSON client, send each document as a base64-encoded string.

  • agent_context_arns (AgentContextOnlyArnList) –

    The ARNs of the agent contexts that the traces are about: 1–10 agent-context/ ARNs that name at most 5 distinct agent contexts, in this Region and partition, all in your account. If you name more, the request fails with ValidationException. AWS Context authorizes context:PutTrace once for each agent context. If any authorization is denied, the whole call fails with AccessDeniedException, and nothing is stored. After authorization, if trace analysis is disabled for an agent context, the call fails with ValidationException, and nothing is stored.

  • trace_metadata (Optional[TraceMetadata], default: None ) –

    Client-supplied key-value pairs, stored with the traces as-is. The key analysisMode is reserved. A request that sets it fails with AccessDeniedException.

  • access_control_config (Optional[AccessControlConfig], default: None ) –

    The principals who can see the insights that AWS Context generates from the traces. If you provide entries, the caller is not included unless an entry names it.

    If you provide no entries (accessControlConfig absent, or accessControlList absent or empty), only the end user that the caller's trusted identity propagation session names can see the insights. If the session names no end user, or there is no session, the call fails with ValidationException and stores nothing. In that case, name the principals, or send ALLOW for * so that every reader of the agent contexts can see the insights.

    An entry other than * without principalType, a principalId that is not valid Unicode, or entries that total more than 65,536 bytes of UTF-8 are rejected with ValidationException. AWS Context stores principal IDs as given and does not verify them against a directory. A session's access control is the union of its traces' entries. A call that would take that union over 100 entries, or over 65,536 bytes of UTF-8, fails with ValidationException and stores nothing.

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.

  • ServiceQuotaExceededException –

    The request would exceed a service quota. Check the quota that quotaCode names, reduce your usage, and then retry the request.

  • UnknownServiceError –

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

Examples:

Submit agent traces for analysis The following example submits two Amazon Bedrock Converse messages from one agent session so that AWS Context can learn from them.

>>> client.put_trace(session_id='sales-analytics-session-0142', client_token='9e4b2d7c-1a5f-4c38-b6e0-2f8d3a7c1b95', format='BEDROCK_CONVERSE', trace_documents=['eyJyb2xlIjoidXNlciIsImNvbnRlbnQiOlt7InRleHQiOiJXaGF0IHdlcmUgdG90YWwgc2FsZXMgaW4gdGhlIFdlc3QgcmVnaW9uIGxhc3QgcXVhcnRlcj8ifV19', 'eyJyb2xlIjoiYXNzaXN0YW50IiwiY29udGVudCI6W3sidGV4dCI6IlRvdGFsIHNhbGVzIGluIHRoZSBXZXN0IHJlZ2lvbiBmb3IgUTMgMjAyNiB3ZXJlIDQuMiBtaWxsaW9uIFVTRCwgZnJvbSBzYWxlcy5vcmRlcnMgZmlsdGVyZWQgb24gcmVnaW9uX2NvZGUgV0UuIn1dfQ=='], agent_context_arns=['arn:aws:context:us-east-1:111122223333:agent-context/ac-3f9c2e7a1b8d4c56a0e4f7b29d1c8e53'], trace_metadata={'agentName': 'sales-analytics-agent', 'agentVersion': '1.4.0'}, access_control_config={'accessControlList': [{'access': 'ALLOW', 'principalId': '*'}]})
Source code in docs_src/capo_context/_services/context.py
def put_trace(
    self,
    format: "capo_context.types.trace_format.TraceFormat",
    trace_documents: "capo_context.types.trace_document_list.TraceDocumentList",
    agent_context_arns: "capo_context.types.agent_context_only_arn_list.AgentContextOnlyArnList",
    *,
    config_overrides: Optional[ContextClientConfig] = None,
    session_id: Optional["capo_context.types.session_id.SessionId"] = None,
    client_token: Optional["capo_context.types.client_token.ClientToken"] = None,
    trace_metadata: Optional[
        "capo_context.types.trace_metadata.TraceMetadata"
    ] = None,
    access_control_config: Optional[
        "capo_context.types.access_control_config.AccessControlConfig"
    ] = None,
) -> "capo_context.types.put_trace_response.PutTraceResponse":
    """<p>Submits an agent's execution traces so that AWS Context can extract reusable knowledge and skills from them. Call it when an agent finishes a task or session that is worth learning from. In <code>agentContextArns</code>, name the agent contexts that the traces are about. AWS Context analyzes the traces for each of them.</p> <p>Each <code>traceDocuments</code> entry is one raw trace document in the trace schema that <code>format</code> selects. You can send 1–100 documents per call. Each document can be up to 5 MiB before encoding. If you use an AWS SDK, pass each document's raw bytes. If you call PutTrace through the agent context's MCP server or another JSON client, send each document as a base64-encoded string. To send a larger trace, split it across calls that share a <code>sessionId</code>.</p> <p> <code>sessionId</code> groups related calls into one session. If you omit it, AWS Context generates one and returns it in the response so that you can reuse it.</p> <p>Each agent context can hold up to 100,000 trace documents. If a request would exceed this quota, it fails with <code>ServiceQuotaExceededException</code>, and AWS Context stores no documents. If a request fails for any other reason, AWS Context might have stored some of its documents. To store the rest without duplicates, retry with the same <code>clientToken</code>.</p>

    Args:
        session_id: <p>The agent session this trace belongs to and the grouping key: multiple PutTrace calls with the same <code>sessionId</code> are one session. Optional. If you omit it, the service generates one and returns it in the response. It is not the <code>traceId</code>: an OTLP batch carries many trace_ids under one session.</p>
        client_token: <p>Makes the call idempotent. A retry with the same token and the same request returns the same <code>sessionId</code> and does not write the traces again. Reusing the token fails with <code>ValidationException</code> if the request is different, or if another caller reuses it when <code>accessControlConfig</code> names no entries. A token is honored for 8 hours after its first use. When <code>accessControlConfig</code> names no entries and the caller's end user cannot be resolved at the time of the retry, the retry fails with <code>ValidationException</code> even if the first attempt stored traces. To complete them, resend with explicit entries under a new token.</p>
        format: <p>The format of the documents in <code>traceDocuments</code>. Valid values:</p> <ul> <li> <p> <code>OTEL</code> - OpenTelemetry traces in OTLP/JSON.</p> </li> <li> <p> <code>ANTHROPIC</code> - Claude Code session logs, one log line per document.</p> </li> <li> <p> <code>BEDROCK_CONVERSE</code> - Amazon Bedrock Converse messages, one message (<code>role</code> and <code>content</code>) per document, in conversation order.</p> </li> <li> <p> <code>KIRO</code> - Kiro IDE or Kiro CLI session logs.</p> </li> </ul>
        trace_documents: <p>The raw trace documents, in the trace schema that <code>format</code> selects. You can send 1–100 documents per call, and each document can be up to 5 MiB (5,242,880 bytes) before encoding. If you use an AWS SDK, pass each document's raw bytes. If you call PutTrace through the agent context's MCP server or another JSON client, send each document as a base64-encoded string.</p>
        agent_context_arns: <p>The ARNs of the agent contexts that the traces are about: 1–10 <code>agent-context/</code> ARNs that name at most 5 distinct agent contexts, in this Region and partition, all in your account. If you name more, the request fails with <code>ValidationException</code>. AWS Context authorizes <code>context:PutTrace</code> once for each agent context. If any authorization is denied, the whole call fails with <code>AccessDeniedException</code>, and nothing is stored. After authorization, if trace analysis is disabled for an agent context, the call fails with <code>ValidationException</code>, and nothing is stored.</p>
        trace_metadata: <p>Client-supplied key-value pairs, stored with the traces as-is. The key <code>analysisMode</code> is reserved. A request that sets it fails with <code>AccessDeniedException</code>.</p>
        access_control_config: <p>The principals who can see the insights that AWS Context generates from the traces. If you provide entries, the caller is not included unless an entry names it.</p> <p>If you provide no entries (<code>accessControlConfig</code> absent, or <code>accessControlList</code> absent or empty), only the end user that the caller's trusted identity propagation session names can see the insights. If the session names no end user, or there is no session, the call fails with <code>ValidationException</code> and stores nothing. In that case, name the principals, or send <code>ALLOW</code> for <code>*</code> so that every reader of the agent contexts can see the insights.</p> <p>An entry other than <code>*</code> without <code>principalType</code>, a <code>principalId</code> that is not valid Unicode, or entries that total more than 65,536 bytes of UTF-8 are rejected with <code>ValidationException</code>. AWS Context stores principal IDs as given and does not verify them against a directory. A session's access control is the union of its traces' entries. A call that would take that union over 100 entries, or over 65,536 bytes of UTF-8, fails with <code>ValidationException</code> and stores nothing.</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.service_quota_exceeded_exception.ServiceQuotaExceededException: <p>The request would exceed a service quota. Check the quota that <code>quotaCode</code> names, reduce your usage, and then retry the request.</p>
        capo_context.errors.UnknownServiceError: The service returned an error code this client does not model.

    Examples:
        Submit agent traces for analysis
        The following example submits two Amazon Bedrock Converse messages from one agent session so that AWS Context can learn from them.

        >>> client.put_trace(session_id='sales-analytics-session-0142', client_token='9e4b2d7c-1a5f-4c38-b6e0-2f8d3a7c1b95', format='BEDROCK_CONVERSE', trace_documents=['eyJyb2xlIjoidXNlciIsImNvbnRlbnQiOlt7InRleHQiOiJXaGF0IHdlcmUgdG90YWwgc2FsZXMgaW4gdGhlIFdlc3QgcmVnaW9uIGxhc3QgcXVhcnRlcj8ifV19', 'eyJyb2xlIjoiYXNzaXN0YW50IiwiY29udGVudCI6W3sidGV4dCI6IlRvdGFsIHNhbGVzIGluIHRoZSBXZXN0IHJlZ2lvbiBmb3IgUTMgMjAyNiB3ZXJlIDQuMiBtaWxsaW9uIFVTRCwgZnJvbSBzYWxlcy5vcmRlcnMgZmlsdGVyZWQgb24gcmVnaW9uX2NvZGUgV0UuIn1dfQ=='], agent_context_arns=['arn:aws:context:us-east-1:111122223333:agent-context/ac-3f9c2e7a1b8d4c56a0e4f7b29d1c8e53'], trace_metadata={'agentName': 'sales-analytics-agent', 'agentVersion': '1.4.0'}, access_control_config={'accessControlList': [{'access': 'ALLOW', 'principalId': '*'}]})
    """

    def _handler(
        req: "OperationRequest[capo_context.types.put_trace_request.PutTraceRequest]",
    ) -> OperationResponse[
        "capo_context.types.put_trace_response.PutTraceResponse"
    ]:
        import capo_context._operations.context.put_trace

        output, http_response = (
            capo_context._operations.context.put_trace.put_trace(
                req.options, req.input
            )
        )
        return OperationResponse(output=output, response=http_response)

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

        return capo_context.types.put_trace_request.redact_sensitive(input_)

    interceptors_, options_ = self.operation_options(
        config_overrides, OperationLogging("PutTrace", redact_input=_redact_input)
    )
    input_: capo_context.types.put_trace_request.PutTraceRequest = {
        "format": format,
        "trace_documents": trace_documents,
        "agent_context_arns": agent_context_arns,
    }
    if session_id is not None:
        input_["session_id"] = session_id
    if client_token is None:
        client_token = str(uuid.uuid4())
    input_["client_token"] = client_token
    if trace_metadata is not None:
        input_["trace_metadata"] = trace_metadata
    if access_control_config is not None:
        input_["access_control_config"] = access_control_config

    response = execute_pipeline(
        OperationRequest(input=input_, options=options_),
        handler=_handler,
        interceptors=list(interceptors_),
    )
    response.response.close()
    return response.output