# Variables and Secrets

Manage reusable values and secure credentials across your Custom Actions.

---

> **Note:** Custom Actions require a Builder plan or higher.
> [Upgrade to Builder](https://app.avcodex.com/plans)

## Application variables

Application variables are reusable values shared across every Custom Action in your AVCodex agent.

### Creating variables

1. Open any Custom Action.
2. Navigate to the **Variables** tab.
3. Click **Add Variable**.

| Field           | Description                            | Example                                  |
| --------------- | -------------------------------------- | ---------------------------------------- |
| **Name**        | Variable identifier (UPPER_SNAKE_CASE) | `API_KEY`                                |
| **Label**       | Display name                           | `API Key`                                |
| **Type**        | Data type                              | `secret`                                 |
| **Value**       | Actual value                           | `sk-abc123...`                           |
| **Description** | Usage notes                            | `Crestron XiO Cloud API key`             |

### Variable types

| Type        | Use case             | Storage                      |
| ----------- | -------------------- | ---------------------------- |
| **string**  | Text values, URLs    | Plain text.                  |
| **number**  | Numeric values       | Plain text.                  |
| **boolean** | True/false flags     | Plain text.                  |
| **secret**  | API keys, passwords  | Encrypted.                   |
| **url**     | Base URLs, endpoints | Plain text with validation.  |

### Using variables

Reference variables with `{{var.VARIABLE_NAME}}` syntax:

```bash
https://{{var.API_DOMAIN}}/v{{var.API_VERSION}}/endpoint

Authorization: Bearer {{var.API_KEY}}
X-Workspace-ID: {{var.WORKSPACE_ID}}

{
  "api_key": "{{var.API_KEY}}",
  "environment": "{{var.ENVIRONMENT}}"
}
```

### Variable resolution

Variables can be used as:

- **Exact match:** the entire value is the variable.
- **Embedded:** a variable inside a larger string.

```bash
{{var.API_KEY}}

Bearer {{var.API_KEY}}
https://{{var.DOMAIN}}/api/v{{var.VERSION}}
```

## System variables

System variables give your Custom Actions runtime context, information about the current conversation, the user, and timing that the platform provides automatically. Unlike application variables (which you define), system variables are built-in and always available.

**When to use system variables**

- Forward conversation context to external AI services.
- Track which tech triggered an action for audit logs.
- Add timestamps to records you create over the API.

### Available system variables

| Variable                           | Type   | Description                                                       |
| ---------------------------------- | ------ | ----------------------------------------------------------------- |
| `{{system.message_history}}`       | Array  | The full conversation up to this point.                           |
| `{{system.message_history_light}}` | Array  | Compact conversation without tool outputs.                        |
| `{{system.user_id}}`               | String | Unique identifier for the current user.                           |
| `{{system.timestamp}}`             | String | Current time in Unix milliseconds.                                |
| `{{system.session_id}}`            | String | Unique identifier for the current chat session.                   |
| `{{system.chat_url}}`              | String | Direct link to the current chat session in AVCodex.               |
| `{{system.chat_transcript_url}}`   | String | API endpoint URL to fetch the chat transcript as JSON.            |
| `{{system.consumer_access_token}}` | String | OAuth access token from consumer authentication.                  |

---

### Message history

**What it is:** the full conversation between the user and your AVCodex agent, formatted for the OpenAI Chat Completions API.

**Why use it:** forward conversation context to another AI service, analyze sentiment, or log interactions to your backend.

**Format**

```json
[
  {
    "role": "system",
    "content": "You are an AV operations assistant."
  },
  {
    "role": "user",
    "content": "Q-SYS Core in Boardroom 4 is offline."
  },
  {
    "role": "assistant",
    "content": "I'll check status now."
  }
]
```

**Available roles**

- `system` - initial instructions (if configured).
- `user` - messages from the human.
- `assistant` - responses from the AVCodex agent.

**Example: forward to OpenAI for additional processing**

```json
{
  "model": "gpt-4",
  "messages": {{system.message_history}},
  "temperature": 0.7
}
```

**Example: send to your analytics backend**

```json
{
  "event": "conversation_snapshot",
  "user_id": "{{system.user_id}}",
  "timestamp": "{{system.timestamp}}",
  "messages": {{system.message_history}}
}
```

> **Warning:** Size consideration. Message history includes the full conversation including tool outputs. For long chats with many tool calls, this can be several KB. If your target API has request size limits, use `{{system.message_history_light}}` instead.

---

### Message history light

**What it is:** a compact version of the conversation that preserves message structure but strips large tool outputs.

**Why use it:** when you need conversation context without full tool results, this dramatically reduces payload size.

**What's included**

- All message `role` and `content` fields.
- Tool invocation metadata (`toolCallId`, `toolName`, `state`).

**What's excluded**

- Tool `input` arguments.
- Tool `output` results (the largest piece).
- Provider metadata.

**Format**

```json
[
  {
    "role": "user",
    "content": "Find recent commissioning reports for the 14th floor"
  },
  {
    "role": "assistant",
    "content": "I found three reports...",
    "toolInvocations": [
      {
        "toolCallId": "call_abc123",
        "toolName": "search_reports",
        "state": "output-available"
      }
    ]
  }
]
```

**Example: forward context to an LLM with size limits**

```json
{
  "model": "gpt-3.5-turbo",
  "messages": {{system.message_history_light}},
  "max_tokens": 500
}
```

**Example: log conversation flow without bloating logs**

```json
{
  "event": "conversation_flow",
  "user_id": "{{system.user_id}}",
  "messages": {{system.message_history_light}}
}
```

> **Note:** When to use each. Use `message_history` when you need complete tool results (forwarding to another AI for analysis). Use `message_history_light` when you only need conversation flow (logging, analytics, APIs with size limits).

---

### User ID

**What it is:** a unique identifier for the person chatting with the agent.

**Why use it:** track actions per tech, create user-specific records, or implement per-user rate limiting in your backend.

**Format:** string (e.g., `"user_abc123"` or `"clx9f2k..."`).

**Example: create a user-specific record**

```json
{
  "user_id": "{{system.user_id}}",
  "action": "submitted_commissioning_note",
  "data": "{{noteText}}"
}
```

**Example: add to request headers for tracking**

```
X-AVCodex-User-ID: {{system.user_id}}
```

> **Note:** The user ID is stable across sessions for the same user. Useful for per-user features in your integrations.

---

### Timestamp

**What it is:** the current time when the action runs, as a Unix timestamp in milliseconds.

**Why use it:** add "created at" timestamps to records, time-based logic, audit trails.

**Format:** string containing milliseconds since the Unix epoch (e.g., `"1713552052000"`).

**Example: log when a record was created**

```json
{
  "created_at": "{{system.timestamp}}",
  "user_id": "{{system.user_id}}",
  "note": "{{noteContent}}"
}
```

**Example: append timestamped data to Google Sheets**

```json
{
  "values": [[
    "{{system.timestamp}}",
    "{{system.user_id}}",
    "{{eventDescription}}"
  ]]
}
```

> **Note:** The timestamp is a string, not a number. If your API expects a numeric timestamp, handle the conversion on your backend.

---

### Session ID

**What it is:** a unique identifier (UUID) for the current chat conversation.

**Why use it:** track specific conversations, link back to chats from your CRM or PM tool, log interactions per session.

**Format:** string (UUID, e.g., `"a1b2c3d4-e5f6-7890-abcd-ef1234567890"`).

**Example: send a session reference to your CRM**

```json
{
  "session_id": "{{system.session_id}}",
  "user_id": "{{system.user_id}}",
  "lead_status": "{{leadStatus}}"
}
```

---

### Chat URL

**What it is:** a direct, clickable link to the current chat session in AVCodex.

**Why use it:** include in webhook payloads so your team can click straight into the conversation from your CRM, Slack, or ticketing system.

**Format:** string (e.g., `"https://app.avcodex.com/w/chat/YourAgent-123/session/abc-123-def"`).

**Example: send chat link to a CRM via webhook**

```json
{
  "lead_name": "{{leadName}}",
  "chat_link": "{{system.chat_url}}",
  "notes": "{{conversationSummary}}"
}
```

> **Note:** Anyone with the link can view the conversation. Use it for internal team tools like CRMs, not for public-facing integrations.

---

### Chat Transcript URL

**What it is:** a URL pointing to the JSON transcript API endpoint for the current chat session.

**Why use it:** include in webhook payloads so your backend can fetch the full conversation as structured JSON. Unlike `chat_url` (which links to a web view), this URL returns machine-readable JSON when called with your agent's API key.

**Format:** string (e.g., `"https://app.avcodex.com/api/v1/chat/transcript/3ace0bfc-6b75-..."`).

**How to use it:** your backend receives this URL in the webhook payload, then calls it with the agent's API key:

```bash
curl -X GET "https://app.avcodex.com/api/v1/chat/transcript/{sessionId}" \
  -H "Authorization: Bearer YOUR_AGENT_API_KEY"
```

**Example: send transcript URL to a CRM via webhook**

```json
{
  "lead_name": "{{leadName}}",
  "chat_link": "{{system.chat_url}}",
  "transcript_api_url": "{{system.chat_transcript_url}}",
  "session_id": "{{system.session_id}}"
}
```

> **Note:** The transcript API requires authentication with your agent's API key (found in the Share tab). See the [Chat Transcript API docs](/docs/api/chat-transcript) for full details on the response format.

---

### Consumer access token

**What it is:** an OAuth access token from consumer authentication providers like Salesforce or Okta.

**Why use it:** forward the authenticated user's credentials to external APIs in Custom Action headers, so actions can run on behalf of the logged-in user.

**Format:** string (JWT or opaque token, e.g., `"eyJhbGciOiJSUzI1NiIs..."`).

**Example: forward user credentials to a Salesforce API**

```
Authorization: Bearer {{system.consumer_access_token}}
```

> **Warning:** This variable is only available when consumer authentication is configured for your agent. It resolves to an empty string if no OAuth provider is set up.

---

### Combining system variables

System variables work alongside application variables and AI-generated parameters:

```json
{
  "api_key": "{{var.API_KEY}}",
  "messages": {{system.message_history}},
  "metadata": {
    "user": "{{system.user_id}}",
    "timestamp": "{{system.timestamp}}",
    "query": "{{searchQuery}}"
  }
}
```

In this example:

- `{{var.API_KEY}}` - your stored API key (application variable).
- `{{system.message_history}}` - conversation context (system variable).
- `{{system.user_id}}` - current user (system variable).
- `{{system.timestamp}}` - current time (system variable).
- `{{searchQuery}}` - value the agent determines from context (AI-generated).

## Security best practices

### 1. Use the secret type for sensitive data

Mark sensitive values as `secret`:

```bash
Type: secret
Name: API_KEY
Value: sk-abc123...

Type: string
Name: API_KEY
Value: sk-abc123...
```

### 2. Never expose secrets in URLs

```bash
https://api.example.com/auth?key={{var.API_KEY}}

Headers:
  Authorization: Bearer {{var.API_KEY}}
```

### 3. Scope variables appropriately

Variables are scoped to agents, not global:

- Each agent has its own variable namespace.
- No cross-agent variable access.
- Per-agent isolation.

### 4. Rotate keys regularly

Update variable values without changing actions:

1. Go to the Variables tab.
2. Update the value.
3. All actions automatically use the new value.

## Common patterns

### Environment configuration

Manage environments with variables:

```bash
API_DOMAIN = api.dev.example.com
ENVIRONMENT = development

API_DOMAIN = api.example.com
ENVIRONMENT = production
```

### Multi-tenant setup

Use variables for tenant-specific values, for example a managed-services AV firm running multiple client agents:

```bash
WORKSPACE_ID = ws_acme_corp
TENANT_KEY = tenant_acme
ORG_ID = org_acme_hq
```

### API versioning

Control API versions centrally:

```bash
API_VERSION = v2
SCHEMA_VERSION = 2024-01-15
CLIENT_VERSION = 1.2.3
```

## Variable management

### Viewing variable usage

See which actions use a variable:

- A green dot indicates usage in the current action.
- Check before deleting variables.
- Updates impact all actions using the variable.

### Import / export

When exporting actions to Collections:

- Variable definitions are included.
- Variable values are NOT exported.
- Importers set their own values.

### Testing variables

Use the action tester to verify resolution:

```bash
URL: {{var.BASE_URL}}/rooms
Header: Bearer {{var.API_KEY}}

URL: https://api.example.com/rooms
Header: Bearer sk-abc123...
```

## AI placeholders

Simple placeholders without a namespace become AI-generated:

```bash
{{userId}}          # Agent determines user ID
{{searchQuery}}     # Agent creates search term
{{ticketSubject}}   # Agent writes a ticket subject

{{var.API_KEY}}     # Application variable
{{system.user_id}}  # System variable
```

## Troubleshooting

### Variables not resolving

1. **Check variable name**

   - Case-sensitive.
   - No spaces.
   - Correct namespace (`var.` or `system.`).

2. **Check variable definition**

   - Variable exists in the Variables tab.
   - Has a value set.
   - Correct type.

3. **Check syntax**

   - Double curly braces: `{{}}`.
   - No extra spaces: `{{var.NAME}}`.
   - Correct namespace prefix.

### Secret values not visible

Secrets are encrypted and never shown after saving:

- This is expected.
- Update the value to change it.
- Use the tester to verify it's working.

### Cross-action dependencies

Variables are resolved per action:

- Define once, use everywhere.
- Changes apply immediately.
- No action rebuild required.

## Next steps

- [Test your actions](/docs/custom-actions/testing-and-debugging)
- [View examples](/docs/custom-actions/examples)
- [Parameter configuration](/docs/custom-actions/parameter-configuration)

*AVCodex · Your AV expertise. Amplified by AI.*
