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:

ExecutionElapsed-time deadline
Recurring jobs and asynchronous event handlers5 minutes
Custom actions called by the AI agent120 seconds
Campaign pre-call handlers60 seconds, because the call waits on them
Custom HTTP endpoints30 seconds
Prompt sectionsAbout 5 seconds, 3 seconds on phone calls
Other Python executions60 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:

GlobalDescription
OCTOCOM_API_BASE_URLBase URL of the API. Append paths such as /rest/v1/website-sources
OCTOCOM_ORG_API_KEYTemporary 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

FieldTypeDescription
conversationdict or NoneThe current conversation: messages, IDs, subject and channel info
businessdictThe business this conversation belongs to
customerdict or NoneThe customer's profile, or None if the customer hasn't been identified
email_threadslistThe conversation's email threads with the addresses on them; empty when it never used email
argsdictArguments passed to custom actions, condition providers, event handlers, and sidebar actions
current_userdictAuthenticated Octocom user who triggered a sidebar action; absent for other execution types
workflowdictThe workflow being evaluated. Only present when the bot runs a condition provider
browser_sessiondict or NoneBrowser session data. Only present for web chat conversations
campaigndict or NoneThe phone campaign and recipient, for conversations from a campaign call
liveCallContextdict (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.

FieldTypeDescription
idstrInternal conversation UUID
publicIdstrShort public ID shown in the dashboard (e.g., "A1B2C3")
urlstrDirect link to this conversation in the Octocom dashboard
subjectstrConversation subject line
businessSlugstrSlug of the business this conversation belongs to
isHandedOffboolWhether the conversation has been handed off to a human agent
isPlaygroundboolTrue for both human playground sessions and automated bot tests. Use testOrigin to tell them apart.
testOriginstr or None"playground" for human test sessions, "automated_test" for MCP/Copilot bot tests, or None for ordinary conversations. Independent of the channel.
initialChannelstr or NoneChannel of the first message (e.g., "web", "email", "instagram")
latestChannelstr or NoneChannel of the most recent message
inboxAddressstr or NoneBusiness mailbox used by the latest email thread. None for conversations without a resolvable email inbox
assigneedict or NoneThe agent currently assigned to the conversation, as {"id": str, "name": str, "email": str}, or None when unassigned
tagslistTitles of the tags currently on the conversation, e.g. ["contact-form", "vip"]. Empty when untagged
metadatadictConversation 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
messageslistArray of message objects (see below)

Messages

Each entry in context["conversation"]["messages"] is a dictionary:

FieldTypeDescription
idstrStable message UUID. Match it to an event's message ID to identify the triggering message.
senderstrWho sent the message: "customer", "bot" or "agent"
timestampstrWhen the message was sent (ISO 8601 format)
contentstrThe message text
channelstrThe channel the message was sent on
agentNamestr or NoneName of the agent who sent the message. Set on agent-sent messages, None otherwise
agentEmailstr or NoneEmail of the agent who sent the message. Set on agent-sent messages, None otherwise
fileslistFiles attached to the message (see below). Empty if none

Message files

Each entry in a message's files list is a dictionary:

FieldTypeDescription
idstrFile unique identifier
namestrOriginal filename
contentTypestrMIME type of the file (e.g., "image/jpeg", "application/pdf")
urlstrDownload URL. For privately stored attachments it is a signed link valid for one hour
isSafeboolWhether 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.

FieldTypeDescription
namestrThe business name
slugstrThe 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).

FieldTypeDescription
idstrInternal customer UUID
emailstr or NoneCustomer email address
namestr or NoneCustomer name
phonestr or NoneCustomer phone number
instagramUsernamestr or NoneCustomer'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 fieldTypeDescription
fromstr or NoneOriginal incoming message's From address, before customer lookup or contact-form rewriting
tolist[str] or NoneOriginal incoming message's To addresses available from the integration, not the addresses our replies go to
inboxAddressstr or NoneReceiving 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 with context["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_type key with the event name (for example "conversation_closed"), plus the event's details under an event-specific key such as rate_limit, phone_call or bot_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:

FieldTypeDescription
idstrInternal Octocom user UUID
namestrUser's display name
emailstrUser'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:

FieldTypeDescription
idstrInternal workflow UUID
slugstrStable workflow slug
titlestrWorkflow 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).

FieldTypeDescription
visitedUrlslist[str]Pages the customer visited in this session
userAgentstr or NoneThe browser's user agent string
browserName, browserVersionstr or NoneThe customer's browser
osName, osVersionstr or NoneThe customer's operating system
deviceType, deviceBrand, deviceModelstr or NoneThe customer's device
ip, countrystr or NoneThe visitor's IP address and country

Other fields

Some function types get a field of their own:

FieldPresent inContents
context["job"]Recurring jobsThe job's ID, name, schedule, timezone, occurrence and trigger. Recurring jobs have no conversation or customer
context["request"]Custom HTTP endpointsThe HTTP method, headers, query and body. Endpoints have no conversation
context["campaign"]Conversations from a phone campaign callThe 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 callSee below

Availability by function type

Not every field is present in every function type:

FieldCustom ActionsCondition ProvidersEvent HandlersSidebar WidgetsSidebar Actions
conversationIf availableIf availableConversation eventsAlwaysAlways
businessAlwaysAlwaysAlwaysAlwaysAlways
customerIf availableIf availableIf availableIf availableIf available
email_threadsAlways ([] without a conversation)Always ([] without a conversation)AlwaysAlwaysAlways
argsAlwaysAlwaysAlwaysNot presentAlways
current_userNot presentNot presentNot presentNot presentAlways
workflowNot presentBot execution onlyNot presentNot presentNot present
browser_sessionWeb chat onlyWeb chat onlyWeb chat onlyWeb chat onlyWeb 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").

FieldTypeDescription
versionintContract version, currently 1
capturedAtstrISO timestamp when the snapshot was taken (not individual message timestamps)
truncatedboolWhether older spoken messages were left out to meet the size limit
messageslistOrdered 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.

On this page