> ## Documentation Index
> Fetch the complete documentation index at: https://docs.argalabs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Capture agent traces

> Collect customer-filtered Gmail and Stripe evidence for Training with Python SDK v0.2.0

Use `arga-py-sdk` **v0.2.0 or later** to wrap your agent's Gmail and Stripe clients. Your process selects fields, filters text, and aliases identities before uploading evidence to [Training](https://docs.argalabs.com/features/training.md).

```bash theme={null}
pip install --upgrade arga-py-sdk
```

Python 3.10+ is required. The standard install includes tracing, Stripe, and the Google API client. Installing or importing the package does not start collection.

```mermaid theme={null}
flowchart LR
  subgraph Customer[Your process]
    A[Agent and provider clients] --> B[Selection, text filter, aliases]
  end
  B -->|Selected evidence| C[Arga Training]
  C --> D[Draft task and verifier]
  D --> E[Your review]
```

Already use Braintrust? Run [customer-side Braintrust sync](https://docs.argalabs.com/sdks/python/braintrust.md) instead of adding live wrappers.

## Create an upload key

Use a full Arga credential outside your agent process to create a source-bound upload key:

```python theme={null}
import os
from arga_sdk import Arga

with Arga(api_key=os.environ["ARGA_API_KEY"]) as arga:
    credential = arga.training.create_upload_key(source="support-agent")
    upload_secret = credential.key.get_secret_value()
    # Store upload_secret in your secret manager as ARGA_TRACE_KEY.
    # Do not print it or include it in traces.
```

The agent needs only `ARGA_TRACE_KEY`. This key can upload evidence for `support-agent`; it cannot read collections, generate tasks, approve tasks, or provision environments. Source names use lowercase letters, digits, `_` or `-`, start with a letter or digit, and contain at most 64 characters.

Keys expire after 30 days. Rotating the account's legacy API key or revoking its sessions invalidates these keys. Individual upload-key revocation is not available in v1.

## Wrap your existing clients

In this example, `stripe_client`, `gmail_service`, and `run_agent` are your existing application objects. Pass the wrapped clients into every provider call you want to capture.

```python theme={null}
from arga_sdk.tracing import CapturePolicy, init

tracing = init(
    source="support-agent",
    policy=CapturePolicy(text_fields=frozenset({"goal", "policy"})),
)
traced_stripe = tracing.wrap_stripe(stripe_client)
traced_gmail = tracing.wrap_gmail(gmail_service)

@tracing.agent(
    goal=lambda request: request["task"],
    policies=[
        "Customer confirmations require the accountable owner's review before sending."
    ],
)
def handle_request(request):
    return run_agent(
        request,
        stripe_client=traced_stripe,
        gmail_service=traced_gmail,
    )
```

Only executed calls through these clients inside an active episode are observed. Wrapping adds no provider requests and preserves provider return values and exceptions. Calls through an unwrapped client are outside collection coverage.

The example selects the request's `task` string and the listed policy. It does not collect your full request object, system prompt, model reasoning, or source code. Share only goal and policy text that your collection policy permits.

For an async agent, use an `async def` entry point with the same decorator. Stripe `*_async` methods are supported. During async shutdown, use `await tracing.aflush(timeout=10)`.

### Explicit episode boundaries

Use an episode around work that does not fit a single decorated function, including generator consumption:

```python theme={null}
with tracing.episode(
    goal="Correct the duplicate payment while preserving the original charge.",
    policies=["Customer confirmations require owner review before sending."],
):
    result = run_agent(request, stripe_client=traced_stripe, gmail_service=traced_gmail)
```

Wait for provider work to finish before leaving the episode. Concurrent reads are accepted. Overlapping reads and writes, or overlapping writes, produce an ordering gap because they cannot establish reliable pre-mutation state.

## Select and filter free text locally

Free text is off by default. A goal is required for task generation, so select at least the objective you intend to share. Gmail subject and plain-text body are separate opt-ins.

To share selected Gmail text, pass your own local filter when configuring the collector. `filter_training_text` below is your application's function, not a function supplied by Arga:

```python theme={null}
policy = CapturePolicy(
    text_fields=frozenset({"goal", "policy", "gmail.subject", "gmail.body"}),
    transform_text=filter_training_text,
    revision="support-v1",
)
tracing = init(source="support-agent", policy=policy)
```

The callback runs locally on selected goal, policy, subject, and body text before built-in masking. It must preserve the business facts needed to reconstruct the task. Keep this callback on your host; do not send raw text to Arga as part of filtering. Bump `revision` when the filter changes.

Built-in masking aliases recognized emails and Stripe IDs and removes common credential formats. It does not reliably remove names, proprietary facts, or every secret format. Use your local filter or supply already-selected task facts for those requirements. A filter failure omits the affected evidence and blocks generation.

### What leaves your process

| Evidence | Collected fields |
| - | - |
| Gmail | Aliased message, draft, thread and actor identities; aliased sender/recipient addresses; labels and dates; selected subject/plain-text body |
| Stripe | Aliased customer/payment/charge/refund relationships; amounts, currency, relevant status, dates and refund state |
| Objective | Only the selected goal and policy strings |
| Coverage | Operation order, resource/page scope, page completeness and collection issues |

The adapters omit provider credentials, request headers, arbitrary metadata, model prompts/reasoning, raw MIME, attachments, HTML and snippets. Their allowlist does not traverse arbitrary response objects.

Omitted fields and unobserved records are unknown. A complete result page does not establish that an entire account is empty or fully captured.

## Preview before uploading

Set `upload=False` to inspect the selected evidence locally. Provider calls still execute against the clients you supply; preview disables Arga uploads.

```python theme={null}
preview = init(source="support-agent", policy=policy, upload=False)
preview_stripe = preview.wrap_stripe(stripe_client)

with preview.episode(goal="Inspect the selected charge for the billing task."):
    charge = preview_stripe.v1.charges.retrieve(charge_id)

selected_evidence = preview.last_episode
# Review selected_evidence locally using your own handling policy.
preview.close()
```

Use your original provider client for `stripe_client` in this standalone example. Inside an episode, `episode.preview()` also returns the current projection.

## Flush and open Training

The collector exports in the background. During graceful shutdown:

```python theme={null}
tracing.flush(timeout=10)
print(tracing.diagnostics())
for receipt in tracing.recent_uploads():
    print("https://app.argalabs.com" + receipt["training_path"])
tracing.close()
```

`flush()` reports queue drainage, not guaranteed delivery. Check the `uploaded`, `failed`, and `dropped` counters. Receipts contain only bounded collection IDs and Training paths. Do not log source payloads or provider exception bodies.

Uploads use a bounded in-memory queue and up to three attempts for transient errors. There is no disk spool. Queue overflow, exhausted attempts, or abrupt termination can lose evidence. Collection failures do not change a wrapped provider's result.

Each accepted episode creates a private, immutable Training collection. Identical evidence deduplicates per owner; revised evidence creates a new collection. Open the receipt to [generate a task and verifier](https://docs.argalabs.com/sdks/python/training.md).

## Coverage and limits

V1 supports Stripe `customers`, `payment_intents`, `charges` and `refunds` through modern `StripeClient.v1` and supported legacy resources. Gmail supports `messages`, `drafts` and profile calls through discovery-client requests executed with `.execute()`. It does not automatically capture batch requests, implicit auto-pagination, streaming lifetimes, arbitrary custom tools, or other providers.

Limits are 100 KB per episode, 100 operations, 50 records per operation, 4,000 characters per selected text field and 10 policy strings. Detected unsupported operations, failed projections, exceeded limits, missing objectives/read observations and incomplete ordering block generation while keeping accepted evidence inspectable.

Selected evidence is retained by the existing Training storage lifecycle and is sent to Arga's configured model provider when you request generation. V1 adds no automatic expiry, continuous source grouping, or new deletion/retention controls. Arga does not execute your agent or train a model as part of this workflow.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.