Skip to content

Python

Python 3.13 is the default language for Function tools and the most commonly used option in the Studio code editor.

Python functions support two compute types: CPU (the default) and GPU. Both run the same handler signature and requirements.txt workflow - GPU just runs on GPU hardware with higher resource limits and machine-learning libraries pre-installed. See GPU compute below.


Handler signature

Your main file must be named cortexone_function.py and must define a function called cortexone_handler:

def cortexone_handler(event, context):
result = {"message": "Hello, World!"}
return {"statusCode": 200, "body": result}
ParameterTypeDescription
eventdictThe input payload sent by the caller
contextobjectExecution metadata

The handler returns a dict with statusCode and body. Return body as a plain dict - the platform serializes it automatically.


The event object

event is whatever JSON the caller passes. For example, if the caller sends:

{ "name": "Alice", "numbers": [1, 2, 3] }

Your handler receives:

def cortexone_handler(event, context):
name = event["name"]
numbers = event["numbers"]
total = sum(numbers)
return {"statusCode": 200, "body": {"greeting": f"Hello, {name}!", "total": total}}

Multiple files

You can upload multiple files. The main entry file must be cortexone_function.py containing cortexone_handler. Additional .py files can be imported using standard imports.

Supported file types: .py, .csv, .md, .txt, .json, .yaml, .yml.


Dependencies

Add a requirements.txt file alongside cortexone_function.py to install third-party packages:

requests==2.31.0
pandas==2.2.0

The platform installs your dependencies before executing your handler.

Common libraries are already available without a requirements.txt entry - for example requests, numpy, pandas, and the Python standard library.


Secrets

Store credentials as Secrets at /user/secrets, attach them to your tool from the Code tab in Studio, and read them at runtime:

import os
def cortexone_handler(event, context):
api_key = os.environ.get("MY_API_KEY", "")
return {"statusCode": 200, "body": {"ready": len(api_key) > 0}}

See Secrets for the full workflow.


Resource limits

LimitDefault
Max memory512 MB
Max runtime300 seconds
CPU limit2.0 cores

GPU functions get higher limits - see GPU compute below.


GPU compute

Python 3.13 supports two compute types: CPU (default) and GPU. Set Compute Type: GPU when creating or editing the tool to run on GPU hardware instead - the handler signature, event/context objects, and requirements.txt workflow are unchanged.

CUDA: 12.4. cuDNN is not baked into the base image - torch (CUDA 12.4 wheels) and tensorflow[and-cuda] each bundle the exact cuDNN build they were compiled against, so you don’t need to install it yourself.

Resource limits on GPU:

LimitDefault
Max memory8192 MB
Max runtime600 seconds

The higher timeout accounts for GPU-specific cold-start cost - pulling model weights, warming the CUDA context, and the first torch/tensorflow import - on top of your handler’s own compute time.

Pre-installed libraries: the packages below are already available on GPU functions without a requirements.txt entry. Add anything else you need to requirements.txt as usual.

PackageNotes
torch, torchvision, torchaudioCUDA 12.4 build
transformersPinned <5.0.0
accelerate, diffusers, safetensors, tokenizers, sentencepiece, huggingface_hubHuggingFace ecosystem
tensorflow2.21.0, with bundled CUDA/cuDNN ([and-cuda])
mineru[core]>=2.7.0 - document layout, OCR, table and formula extraction. Models are downloaded on first use, not baked into the image
spacy, misaki, kokoroText-to-speech pipeline
pyparsing>=3.1
numpy, scipy, pillow, pandas, requests, pydanticSame as the standard Python 3.13 runtime

Example: Processing numbers

import pandas as pd
def cortexone_handler(event, context):
s = pd.Series(event["num"])
return {"statusCode": 200, "body": {"sum": float(s.sum()), "mean": float(s.mean())}}

Example: HTTP request

import requests
def cortexone_handler(event, context):
url = event.get("url")
response = requests.get(url, timeout=10)
return {
"statusCode": 200,
"body": {
"status_code": response.status_code,
"text": response.text[:500]
}
}

The context object

Python handlers receive a context object with execution metadata:

FieldDescription
context.function_nameThe tool’s function identifier
context.memory_limit_in_mbAllocated memory in MB
context.remaining_time_in_millisMilliseconds remaining before timeout
context.get_remaining_time_in_millis()Method - same as the field above

Error responses

If your handler raises an exception, the platform catches it and returns:

{
"statusCode": 500,
"body": "{\"error\": \"Runtime error: <message>\"}"
}

Timeouts return statusCode: 408. You can also return non-200 status codes intentionally:

def cortexone_handler(event, context):
if not event.get("id"):
return {"statusCode": 400, "body": {"error": "id is required"}}
return {"statusCode": 200, "body": {"ok": True}}

Testing your code

Save and run sample payloads from the Preview tab in Studio. The panel shows the returned statusCode, body, and any logs from your handler. See Testing & Executing for the full workflow.


Notes

  • Each run starts fresh - no files persist between runs and no globals carry over.
  • The main file must be named cortexone_function.py and must contain cortexone_handler.
  • JavaScript (V8) and Lua handlers do not receive a populated context parameter; Node.js handlers get their own camelCase context.
  • For lower-latency execution without outbound HTTP, consider Python 3.13 — Fast.