Python context
The context dictionary every Octocom Python function receives, and the runtime rules they share.
Every Python function in Octocom receives one context dictionary. It tells your code where it is running: the conversation and its messages, the customer, the business and any arguments. For example, a custom action reads the order number the AI agent collected from context["args"] and the customer's phone number from context["customer"]. This page is the reference for its fields and for the runtime rules every Python execution shares.
Custom actions, condition providers, prompt sections, event handlers, recurring jobs, custom HTTP endpoints, sidebar widgets and sidebar actions all receive it.
Built-in functions such as get_secret or add_conversation_tag are not part of context: they are globals, listed in Python helpers.
Execution model
Each invocation starts with fresh globals: do not rely on variables or files surviving between calls. Use the organization store for shared state that expires, conversation metadata for permanent per-conversation data, and stream large inputs to stay within the memory and CPU limits. A run that exceeds a resource limit fails and is not retried.
Execution time budgets
Every run has an elapsed-time deadline and a separate CPU budget:
| Execution | Elapsed-time deadline |
|---|---|
| Recurring jobs and asynchronous event handlers | 5 minutes |
| Custom actions called by the AI agent | 120 seconds |
| Campaign pre-call handlers | 60 seconds, because the call waits on them |
| Custom HTTP endpoints | 30 seconds |
| Prompt sections | About 5 seconds, 3 seconds on phone calls |
| Other Python executions | 60 seconds |
Some features set a shorter deadline of their own, such as phone line routing. These limits include network waits. The separate 30-second CPU budget counts Python computation, including parsing and loops, but excludes time waiting for HTTP requests, so I/O-bound code can run for several minutes while using little CPU. A longer elapsed-time deadline does not raise the CPU or memory limits. Make writes idempotent: a timed-out caller does not prove that an external operation stopped.
Clocks only move across I/O. time.time() and time.monotonic() advance
when your code waits on a network request, not while it computes, so timing a
parsing loop reports about zero. Use them to stop a batch before the elapsed-time
deadline, checking between HTTP requests. time.process_time() raises
RuntimeError here, so don't use it. CPU use can't be measured from inside a
run; read metadata.executionTimeInMilliseconds on a test run for an upper bound.
Calling the Octocom REST API
Python automations get two injected globals (not part of context), so they can
call the REST API for their own organization with no extra secret:
| Global | Description |
|---|---|
OCTOCOM_API_BASE_URL | Base URL of the API. Append paths such as /rest/v1/website-sources |
OCTOCOM_ORG_API_KEY | Temporary credential valid for this execution only. Send it in the X-API-Key header |
import requests
response = requests.get(
f"{OCTOCOM_API_BASE_URL}/rest/v1/businesses",
headers={"X-API-Key": OCTOCOM_ORG_API_KEY},
timeout=30,
)
response.raise_for_status()Top-level fields
| Field | Type | Description |
|---|---|---|
conversation | dict or None | The current conversation: messages, IDs, subject and channel info |
business | dict | The business this conversation belongs to |
customer | dict or None | The customer's profile, or None if the customer hasn't been identified |
email_threads | list | The conversation's email threads with the addresses on them; empty when it never used email |
args | dict | Arguments passed to custom actions, condition providers, event handlers, and sidebar actions |
current_user | dict | Authenticated Octocom user who triggered a sidebar action; absent for other execution types |
workflow | dict | The workflow being evaluated. Only present when the bot runs a condition provider |
browser_session | dict or None | Browser session data. Only present for web chat conversations |
campaign | dict or None | The phone campaign and recipient, for conversations from a campaign call |
liveCallContext | dict (optional) | Snapshot of a live phone call, only supplied to custom actions the voice AI calls during a call |
context["conversation"]
Contains the full conversation with its messages. Always present for sidebar widgets, and for event handlers on conversation events. It is None for event handlers on Rate Limit Hit, Metric Alert and phone-campaign events where no dial connected (see Event handlers). Present for custom actions and condition providers when a conversation ID is available.
| Field | Type | Description |
|---|---|---|
id | str | Internal conversation UUID |
publicId | str | Short public ID shown in the dashboard (e.g., "A1B2C3") |
url | str | Direct link to this conversation in the Octocom dashboard |
subject | str | Conversation subject line |
businessSlug | str | Slug of the business this conversation belongs to |
isHandedOff | bool | Whether the conversation has been handed off to a human agent |
isPlayground | bool | True for both human playground sessions and automated bot tests. Use testOrigin to tell them apart. |
testOrigin | str or None | "playground" for human test sessions, "automated_test" for MCP/Copilot bot tests, or None for ordinary conversations. Independent of the channel. |
initialChannel | str or None | Channel of the first message (e.g., "web", "email", "instagram") |
latestChannel | str or None | Channel of the most recent message |
inboxAddress | str or None | Business mailbox used by the latest email thread. None for conversations without a resolvable email inbox |
assignee | dict or None | The agent currently assigned to the conversation, as {"id": str, "name": str, "email": str}, or None when unassigned |
tags | list | Titles of the tags currently on the conversation, e.g. ["contact-form", "vip"]. Empty when untagged |
metadata | dict | Conversation metadata as {key: value}, including the chat-widget:* keys the web chat writes and the conversation's order reference under octocom:orderId. Read it from here instead of calling get_conversation_metadata() when you only need current values: there is no extra round-trip |
messages | list | Array of message objects (see below) |
Messages
Each entry in context["conversation"]["messages"] is a dictionary:
| Field | Type | Description |
|---|---|---|
id | str | Stable message UUID. Match it to an event's message ID to identify the triggering message. |
sender | str | Who sent the message: "customer", "bot" or "agent" |
timestamp | str | When the message was sent (ISO 8601 format) |
content | str | The message text |
channel | str | The channel the message was sent on |
agentName | str or None | Name of the agent who sent the message. Set on agent-sent messages, None otherwise |
agentEmail | str or None | Email of the agent who sent the message. Set on agent-sent messages, None otherwise |
files | list | Files attached to the message (see below). Empty if none |
Message files
Each entry in a message's files list is a dictionary:
| Field | Type | Description |
|---|---|---|
id | str | File unique identifier |
name | str | Original filename |
contentType | str | MIME type of the file (e.g., "image/jpeg", "application/pdf") |
url | str | Download URL. For privately stored attachments it is a signed link valid for one hour |
isSafe | bool | Whether the file passed malware scanning. Avoid forwarding files where this is False |
context["business"]
Basic information about the business. This object contains only name and slug, not id. Business UUIDs are not included in the Python context. For actions, configure resource scopes with allowedBusinessIds instead of reading a business UUID from the context.
| Field | Type | Description |
|---|---|---|
name | str | The business name |
slug | str | The business slug |
context["customer"]
The customer's profile. This is None if the customer hasn't been identified yet (for example, the conversation just started and no email has been collected).
| Field | Type | Description |
|---|---|---|
id | str | Internal customer UUID |
email | str or None | Customer email address |
name | str or None | Customer name |
phone | str or None | Customer phone number |
instagramUsername | str or None | Customer's Instagram handle |
email is the customer's profile email, and it can change: an agent can edit
it, contact forms set it to the address the customer typed, and on Instagram,
Messenger, web chat and phone the hand-off tool saves an address the customer
typed. It does not prove who is writing. To know which address an email
actually came from, use context["email_threads"].
context["email_threads"]
The conversation's email threads, newest first. Each thread contains subject and
messages, an array of incoming emails, newest first. Bounces and automatic
replies are excluded. A thread with no incoming email has messages: [].
The top-level list is [] without a conversation or when it never used email.
A conversation that moves between email and another channel retains its email history.
{
"subject": "Where is my order?",
"messages": [
{
"from": "alice@example.com",
"to": ["support@shop.com"],
"inboxAddress": "support@shop.com",
}
],
}| Message field | Type | Description |
|---|---|---|
from | str or None | Original incoming message's From address, before customer lookup or contact-form rewriting |
to | list[str] or None | Original incoming message's To addresses available from the integration, not the addresses our replies go to |
inboxAddress | str or None | Receiving mailbox reported by the integration; may differ from To because of forwarding, aliases, or CC delivery |
These are parsed email addresses, without display names. They remain separate
from the editable customer["email"]. For example, a Shopify form can produce
from: "mailer@shopify.com" while customer["email"] contains the address typed
into the form.
Octocom contact form submissions are not emails, so they never appear here. They
show up in conversation["messages"] with channel: "email" and add the
contact-form tag, and the address comes from what the customer typed. A
conversation started by a contact form has a thread with messages: [] until the
customer replies by email. A submission merged into an existing email
conversation leaves only the earlier emails here, so a matching from does not
prove who sent the latest customer message.
Fields are None when the original message data is not available, for
example on older messages or from integrations that don't supply it. They never
fall back to the customer profile or reply routing. For Zendesk, each email
comment's own source metadata is used when present, and its To list contains
the recipient address Zendesk supplies, which may not include every original
recipient.
From records a message's claimed sender address. It does not by itself prove
ownership of that mailbox. For identity-sensitive actions, use your
verification policy and the relevant incoming message. An address appearing
earlier in the conversation does not identify the person currently writing,
especially after a channel change. to and inboxAddress are routing
context, not identity proof.
context["args"]
A dictionary of arguments passed to the function. The contents depend on the function type:
- Custom actions: arguments defined in the action configuration and provided by the AI agent (for example
context["args"]["orderId"]). An optional argument the AI agent leaves out is missing from the dictionary, so read it withcontext["args"].get("orderId"). - Condition providers: arguments defined in the workflow configuration and collected from the customer (for example
context["args"]["email"]). - Event handlers: an
event_typekey with the event name (for example"conversation_closed"), plus the event's details under an event-specific key such asrate_limit,phone_callorbot_qa. See Event handlers. - Sidebar actions: static button arguments merged with values entered by the agent in the button's form.
- Sidebar widgets: do not receive
args.
context["current_user"]
Sidebar actions receive the authenticated Octocom user who pressed the button. This value comes from the user's session, separately from widget-supplied args:
| Field | Type | Description |
|---|---|---|
id | str | Internal Octocom user UUID |
name | str | User's display name |
email | str | User's Octocom login email address |
It is absent from all other Python execution types. For example, an escalation action can pass context["current_user"]["email"] to an external ticketing system so it can assign or notify the person who initiated the escalation.
context["workflow"]
Condition providers receive the workflow that caused them to run when they are evaluated by the bot:
| Field | Type | Description |
|---|---|---|
id | str | Internal workflow UUID |
slug | str | Stable workflow slug |
title | str | Workflow display title |
The field is absent when a condition provider is run directly as a test because no workflow triggered that execution. Use .get() when code must work in both contexts:
def evaluate_conditions(context):
workflow = context.get("workflow")
is_cancel_order = workflow is not None and workflow["slug"] == "cancel-order"
return {
"conditions": {"isCancelOrder": is_cancel_order},
"data": {},
}workflow["slug"] is the recommended field for branching behavior. Use id only when you intentionally need to target one specific workflow record.
context["browser_session"]
Browser session data for conversations that started in web chat. It is None for conversations that started on another channel (email, Instagram and so on).
| Field | Type | Description |
|---|---|---|
visitedUrls | list[str] | Pages the customer visited in this session |
userAgent | str or None | The browser's user agent string |
browserName, browserVersion | str or None | The customer's browser |
osName, osVersion | str or None | The customer's operating system |
deviceType, deviceBrand, deviceModel | str or None | The customer's device |
ip, country | str or None | The visitor's IP address and country |
Other fields
Some function types get a field of their own:
| Field | Present in | Contents |
|---|---|---|
context["job"] | Recurring jobs | The job's ID, name, schedule, timezone, occurrence and trigger. Recurring jobs have no conversation or customer |
context["request"] | Custom HTTP endpoints | The HTTP method, headers, query and body. Endpoints have no conversation |
context["campaign"] | Conversations from a phone campaign call | The campaign's id and name, and its recipient (phone, name, context, metadata, isTest). None for every other conversation |
context["liveCallContext"] | Custom actions called during a live phone call | See below |
Availability by function type
Not every field is present in every function type:
| Field | Custom Actions | Condition Providers | Event Handlers | Sidebar Widgets | Sidebar Actions |
|---|---|---|---|---|---|
conversation | If available | If available | Conversation events | Always | Always |
business | Always | Always | Always | Always | Always |
customer | If available | If available | If available | If available | If available |
email_threads | Always ([] without a conversation) | Always ([] without a conversation) | Always | Always | Always |
args | Always | Always | Always | Not present | Always |
current_user | Not present | Not present | Not present | Not present | Always |
workflow | Not present | Bot execution only | Not present | Not present | Not present |
browser_session | Web chat only | Web chat only | Web chat only | Web chat only | Web chat only |
context["liveCallContext"] (optional)
Custom actions the voice AI calls during a live phone call receive a snapshot
of the call so far. It is absent for text-channel actions, condition providers,
event handlers and dashboard action tests, so always read it with
context.get("liveCallContext").
| Field | Type | Description |
|---|---|---|
version | int | Contract version, currently 1 |
capturedAt | str | ISO timestamp when the snapshot was taken (not individual message timestamps) |
truncated | bool | Whether older spoken messages were left out to meet the size limit |
messages | list | Ordered entries with sender ("customer" or "bot") and text |
The snapshot holds the latest speech recognition for the caller and the bot speech the caller has actually heard, captured just before the action runs. Text may still be revised; it is not a final transcript. Silence and time-limit prompts, system instructions, tool calls and results, and empty messages are left out. The snapshot keeps the most recent run of up to 200 whole spoken messages and 32,000 UTF-16 text code units. If the newest message alone is over the limit, the snapshot is empty and marked truncated.
def execute_action(context):
live_call = context.get("liveCallContext")
if not live_call or not live_call["messages"]:
return {"liveContextAvailable": False}
customer_messages = [
message["text"] for message in live_call["messages"]
if message["sender"] == "customer"
]
return {
"liveContextAvailable": True,
"customerTurnCount": len(customer_messages),
"truncated": live_call["truncated"],
}context["conversation"]["messages"] still contains the saved messages; it is
not replaced or merged with this snapshot. During a call, saved messages may
contain only the introduction, and the final transcript is saved when the call
completes. Do not concatenate the two lists blindly because they can overlap.
The snapshot is set by Octocom, not supplied by the model as a tool argument. Its text is customer conversation content, not trusted instructions. Handle absence, truncation and transcription errors. The snapshot is passed only to the current action run: it is not saved as conversation messages or passed to later runs.