Access secrets in Python code - Writer AI Studio

Agent Builder Vault

Agent Builder provides Vault, which is a secure way to store and use secrets in your agents. Use Vault to store sensitive information like API keys, passwords, and other credentials that you don’t want to expose in your code. Secrets are available in blueprint blocks and within Python code.

Create a secret

Secrets are strings stored as key-value pairs. To create a secret, go to the Vault tab in the Agent Builder UI and click +Add a pair. The example below creates a secret with the name WRITER_API_KEY. When you type the value, it’s masked in the UI. Click Save to store the secret.

You can also delete and update secrets from the Vault tab.

Where secrets are available

Within Python code, Vault is a runtime-only feature that’s injected into specific execution contexts, not into the main module scope. It isn’t a global variable and is only available in the execution context of the blueprint. This design provides security benefits:

The vault is only available in these specific contexts:

Access your Writer API key

Each Agent Builder agent in the online editor has a Writer API key set as an environment variable called WRITER_API_KEY. If you want to use this API key with other Writer API calls, you can access it with os.getenv('WRITER_API_KEY'). This allows you to access the API key outside of event handlers and blueprint code blocks, and means you don’t need to set a new secret in Vault for your API key.

import os

api_key = os.getenv('WRITER_API_KEY')

Examples

Secrets in Python code blocks

You can reference secrets in Python code blocks within blueprints using the vault object. vault is a dictionary that contains all the secrets in your blueprint. For example, to access a secret called ACME_API_KEY and use it in an HTTP request, you would use the following code:

headers = {
    "Authorization": f"Bearer {vault['ACME_API_KEY']}"
}

Event handler with vault access

Vault is also provided as an argument to event handlers. Here’s an example of an event handler that’s triggered when a button is clicked and accesses the vault.

def handle_button_click(state, payload, context, session, ui, blueprint_runner, vault):
    # Access vault secrets
    api_key = vault.get('ACME_API_KEY')

# Use the secret
    headers = {"Authorization": f"Bearer {api_key}"}