> ## Documentation Index
> Fetch the complete documentation index at: https://docs.notte.cc/llms.txt
> Use this file to discover all available pages before exploring further.

# Function Management

> Update, version, monitor, and manage your deployed Functions

> [!TIP]
>
> Read [the Notte skill](https://notte.cc/skill.md) and follow its setup instructions when setting up Notte or building browser automation. This is the shared source for CLI setup, authentication, and the browser-to-code workflow.

Manage the lifecycle of your Functions including updates, versioning, and monitoring executions.

## Viewing Functions

### List All Functions

View your deployed Functions:

```python list_functions.py theme={null}
from notte_sdk import NotteClient

client = NotteClient()

# List all functions
functions = client.functions.list()

for func in functions.items:
    print(f"ID: {func.function_id}")
    print(f"Name: {func.name}")
    print(f"Version: {func.latest_version}")
    print(f"Created: {func.created_at}")
    print("---")
```

List calls are paginated (10 items per page by default, up to 100 with `page_size`). Use `page` and the response's `has_next` to read further pages. In Python, `client.functions.list()` and `list_runs()` default to `only_active=True`.

### Get Function Details

Retrieve specific Function information:

Set `function_id` (Python) or `functionId` (Node) to your deployed Function's ID.

```python get_function_details.py theme={null}
from notte_sdk import NotteClient

client = NotteClient()

# Get function by ID
function = client.Function(function_id=function_id)

# Access function properties
print(f"Function ID: {function.function_id}")
print(f"Name: {function.response.name}")
print(f"Description: {function.response.description}")
print(f"Latest Version: {function.response.latest_version}")
print(f"Versions: {function.response.versions}")
```

```typescript get_function_details.ts theme={null}
import { NotteClient } from 'notte-sdk';

const client = new NotteClient();

// Get function by ID
const fn = client.NotteFunction({ function_id: functionId });
const response = await fn.get();

// Access function properties
console.log(`Function ID: ${response.function_id}`);
console.log(`Name: ${response.name}`);
console.log(`Description: ${response.description}`);
console.log(`Latest Version: ${response.latest_version}`);
console.log(`Versions: ${response.versions}`);
```

## Updating Functions

### Update Function Code

Deploy a new version of your Function:

```python update_code.py theme={null}
from notte_sdk import NotteClient

client = NotteClient()

function = client.Function(function_id="func_abc123")

# Update with new code
function.update(path="updated_function.py")

print(f"Updated to version: {function.response.latest_version}")
```

### Update Function Metadata

Change metadata with `PATCH /functions/{function_id}`, `client.functions.metadata_update()` in Python, or `fn.updateMetadata()` in TypeScript.

Set `function_id` / `functionId` to your function ID. For Python, also set `api_url` and `api_key`.

```python update_metadata.py theme={null}
import requests

endpoint = f"{api_url}/functions/{function_id}"
headers = {"Authorization": f"Bearer {api_key}"}
response = requests.patch(
    endpoint,
    headers=headers,
    json={"name": "Price monitor", "description": "Checks competitor prices"},
    timeout=30,
)
response.raise_for_status()
metadata = requests.get(endpoint, headers=headers, timeout=30)
metadata.raise_for_status()
print(metadata.json()["name"])
```

```typescript update_metadata.ts theme={null}
import { NotteClient } from 'notte-sdk';

const client = new NotteClient();
const fn = client.NotteFunction({ function_id: functionId });
await fn.updateMetadata({ name: 'Price monitor', description: 'Checks competitor prices' });
const metadata = await fn.get();
console.log(metadata.name);

```

**Note:** Code updates create new versions automatically. Previous versions remain available for rollback.

## Versioning

### Version Management

Functions automatically version on each update:

```python version_management.py theme={null}
from notte_sdk import NotteClient

client = NotteClient()

function = client.Function(function_id=function_id)

# Get all versions
print(f"Available versions: {function.response.versions}")

# Get latest version
print(f"Latest: {function.response.latest_version}")
```

```typescript version_management.ts theme={null}
import { NotteClient } from 'notte-sdk';

const client = new NotteClient();

const fn = client.NotteFunction({ function_id: functionId });
const response = await fn.get();

// Get all versions
console.log('Available versions:', response.versions);

// Get latest version
console.log(`Latest: ${response.latest_version}`);
```

### Run a Specific Version

A run executes the latest version unless you pass `version`, one of the values in `versions`. Use it to keep production on a known-good version while you test changes: `update` adds new versions, and runs that pass `version` keep executing the one they name.

Pass `version` to `function.run()` or `function.create_run()` in Python, `fn.run(variables, { version })` or `fn.createRun({ version })` in TypeScript, or in the body of `POST /functions/{function_id}/runs/start` over HTTP. A run keeps the version it was created with, so for a run made with `create_run()`, pass `version` there. An unknown version returns 404. Only the function's owner can choose a version other than the latest.

### Roll Back to a Previous Version

Rolling back changes the latest version itself, so it affects every run that does not pass `version`, including schedules. Roll back with `POST /functions/{function_id}/rollback` and a version from `versions`, or `fn.rollback({ version })` in TypeScript. The old code is redeployed as a new latest version, and runs pinned to a version are unaffected.

This example pins runs to a version, then rolls back:

```python run_specific_version.py theme={null}
import requests
from notte_sdk import NotteClient

client = NotteClient()

function = client.Function(function_id="func_abc123")
print(function.response.versions)

# Without a version, a run executes the latest version
result = function.run(url="https://example.com")

# Pin a run to a saved version, for example a known-good one
known_good = function.response.versions[0]
pinned = function.run(version=known_good, url="https://example.com")

# A run created ahead of time keeps the version it was created with
created = function.create_run(version=known_good)
later = function.run(function_run_id=created.function_run_id, url="https://example.com")

# Rolling back redeploys the old code as a new latest version, for every
# run that does not pass a version
response = requests.post(
    f"https://api.notte.cc/functions/{function.function_id}/rollback",
    headers={"Authorization": "Bearer YOUR_API_KEY"},
    json={"version": known_good},
)
response.raise_for_status()
print(response.json()["latest_version"])
```

### Version History

Track changes across versions:

```python version_history.py theme={null}
from notte_sdk import NotteClient

client = NotteClient()

functions = client.functions.list()

for func in functions.items:
    print(f"Function: {func.name}")
    print(f"Versions: {', '.join(func.versions)}")
    print(f"Latest: {func.latest_version}")
```

```typescript version_history.ts theme={null}
import { NotteClient } from 'notte-sdk';

const client = new NotteClient();

const functions = await client.functions.list();

for (const fn of functions) {
  console.log(`Function: ${fn.name}`);
  console.log(`Versions: ${fn.versions.join(', ')}`);
  console.log(`Latest: ${fn.latest_version}`);
}
```

## Monitoring Executions

### View Run History

List recent Function executions:

Before running this example, set `function_id` (Python) or `functionId` (Node)
to the ID of the Function whose history you want to inspect. Pass `only_active=False` to include finished and failed runs.

```python view_run_history.py theme={null}
from notte_sdk import NotteClient

client = NotteClient()

# Get recent runs
runs = client.functions.list_runs(
    function_id=function_id,
    only_active=False,  # Include completed runs
)

for run in runs.items:
    print(f"Run ID: {run.function_run_id}")
    print(f"Status: {run.status}")
    print(f"Created: {run.created_at}")
    print(f"Updated: {run.updated_at}")
    print("---")
```

```typescript view_run_history.ts theme={null}
import { NotteClient } from 'notte-sdk';

const client = new NotteClient();

// Get recent runs
const runs = await client.NotteFunction({ function_id: functionId }).runs({
  only_active: false, // Include completed runs
});

for (const run of runs.items) {
  console.log(`Run ID: ${run.function_run_id}`);
  console.log(`Status: ${run.status}`);
  console.log(`Created: ${run.created_at}`);
  console.log(`Updated: ${run.updated_at}`);
  console.log('---');
}
```

### Check Run Status

Monitor specific execution:

Set `function_id` and `run_id` (Python), or `functionId` and `runId` (Node),
to your Function's ID and the run ID returned by its execution.

```python check_run_status.py theme={null}
from notte_sdk import NotteClient

client = NotteClient()

# Get run details
run_status = client.functions.run_get_metadata(function_id, run_id)

print(f"Status: {run_status.status}")  # "active", "closed", "failed"
print(f"Result: {run_status.result}")
print(f"Session ID: {run_status.session_id}")
```

```typescript check_run_status.ts theme={null}
import { NotteClient } from 'notte-sdk';

const client = new NotteClient();

// Get run details
const runStatus = await client.NotteFunction({ function_id: functionId }).getRun(runId);

console.log(`Status: ${runStatus.status}`); // "active", "closed", "failed"
console.log('Result:', runStatus.result);
console.log(`Session ID: ${runStatus.session_id}`);
```

**Status values:**

* `active` - Function is currently running
* `closed` - Function completed successfully
* `failed` - Function encountered an error

### Filter Active Runs

View only running executions:

```python filter_active_runs.py theme={null}
from notte_sdk import NotteClient

client = NotteClient()

# Get only active runs
active_runs = client.functions.list_runs(function_id, only_active=True)

print(f"Active runs: {len(active_runs.items)}")

for run in active_runs.items:
    print(f"Run {run.function_run_id} - {run.status}")
```

```typescript filter_active_runs.ts theme={null}
import { NotteClient } from 'notte-sdk';

const client = new NotteClient();

// Get only active runs
const activeRuns = await client.NotteFunction({ function_id: functionId }).runs({ only_active: true });

console.log(`Active runs: ${activeRuns.items.length}`);

for (const run of activeRuns.items) {
  console.log(`Run ${run.function_run_id} - ${run.status}`);
}
```

## Managing Runs

### Stop Running Function

Cancel a long-running execution:

```python stop_running.py theme={null}
from notte_sdk import NotteClient

client = NotteClient()

# Stop specific run
client.functions.run_stop("function_abc123", "run_xyz789")

print("Function execution stopped")
```

### Monitoring Long Runs

Track execution progress:

```python monitor_runs.py theme={null}
import time
from concurrent.futures import ThreadPoolExecutor

from notte_sdk import NotteClient

client = NotteClient()

function = client.Function(function_id=function_id)

# Create the run first so you know its ID
run_id = function.create_run().function_run_id

# run() blocks until completion; keep its exception visible to the polling thread.
with ThreadPoolExecutor(max_workers=1) as executor:
    execution = executor.submit(
        function.run,
        function_run_id=run_id,
        url="https://example.com",
        stream=False,
    )

    # Poll status while it runs
    while True:
        if execution.done():
            execution.result()  # Propagate a rejected start instead of polling forever.
        status = client.functions.run_get_metadata(function_id, run_id)
        print(f"Status: {status.status}")
        if status.status in ["closed", "failed"]:
            print(f"Final result: {status.result}")
            break
        time.sleep(5)  # Check every 5 seconds

    execution.result()
```

```typescript monitor_runs.ts theme={null}
import { setTimeout as sleep } from 'node:timers/promises';
import { NotteClient } from 'notte-sdk';

const client = new NotteClient();

const fn = client.NotteFunction({ function_id: functionId });

// Create the run first so you know its ID
const { function_run_id: runId } = await fn.createRun();

// Start it without awaiting: run() resolves only when the run finishes
let callError: unknown;
const execution = fn
  .run({ url: 'https://example.com' }, { functionRunId: runId, stream: false })
  .catch((error: unknown) => {
    callError = error;
  });

// Poll status while it runs
while (true) {
  if (callError) {
    console.log('Run failed:', callError);
    break;
  }

  const status = await fn.getRun(runId);

  console.log(`Status: ${status.status}`);

  if (status.status === 'closed' || status.status === 'failed') {
    console.log('Final result:', status.result);
    break;
  }

  await sleep(5000); // Check every 5 seconds
}

await execution;
```

## Forking Functions

### Fork Shared Function

Create your own copy of a shared Function:

```python fork_function.py theme={null}
from notte_sdk import NotteClient

client = NotteClient()

# Fork a function from marketplace or teammate
original = client.Function(function_id="func_abc123")
forked_function = original.fork()

print(f"Forked function ID: {forked_function.function_id}")
print("Original ID: func_abc123")
```

**Use cases:**

* Customize shared Functions
* Create templates from marketplace
* Copy teammate's Functions
* Experiment without affecting original

### Modify Forked Function

After forking, update as needed:

```python modify_forked.py theme={null}
from notte_sdk import NotteClient

client = NotteClient()

# Fork function
original = client.Function(function_id="shared_function_id")
forked = original.fork()

# Update your copy
forked.update(path="my_modified_version.py")

# Run your version
result = forked.run(url="https://example.com")
```

## Downloading Functions

### Download Function Code

Retrieve Function source code:

```python download_code.py theme={null}
from notte_sdk import NotteClient

client = NotteClient()

# Notte-managed functions also need decryption_key="..."
function = client.Function(function_id="func_abc123")

# Download function code
code = function.download()

print(code)  # Function source code

# Or download directly to a file
code = function.download(path="downloaded_function.py")
```

**Requirements:**

* Only works for Functions you own or have access to
* Notte-managed functions also need their decryption key, passed as `decryption_key` when creating the Function instance

### Download for Backup

Back up all your Functions:

```python backup_functions.py theme={null}
import os

from notte_sdk import NotteClient

client = NotteClient()

functions = client.functions.list()

# Create backup directory
os.makedirs("function_backups", exist_ok=True)

for func in functions.items:
    function = client.Function(function_id=func.function_id, decryption_key="your-key")

    try:
        code = function.download()

        filename = f"function_backups/{func.name}_{func.latest_version}.py"
        with open(filename, "w") as f:
            f.write(code)

        print(f"Backed up: {func.name}")
    except Exception as e:
        print(f"Failed to backup {func.name}: {e}")
```

## Deleting Functions

### Delete Function

Remove a Function permanently. The SDKs ask you to confirm with `confirm=True` in Python or `{ confirm: true }` in Node:

```python delete_function.py theme={null}
from notte_sdk import NotteClient

client = NotteClient()

function = client.Function(function_id="func_abc123")

# Delete function
function.delete(confirm=True)

print("Function deleted")
```

**Warning:**

* Deletion is permanent
* All versions are deleted
* Cannot be undone

### Protect a Function from Deletion

Turn on deletion protection for Functions you rely on in production. While it's on, the Function can't be deleted from the console, API, SDK or CLI, and a delete returns `409`. Code updates, rollbacks and runs still work.

```python deletion_protection.py theme={null}
from notte_sdk import NotteClient

client = NotteClient()
function = client.Function(function_id=function_id)

# Protect the function: deletes are refused until this is turned off
function.set_deletion_protection(True)
protected = function.response.deletion_protected
print(protected)

# Turning it off takes the key of a workspace admin or owner
function.set_deletion_protection(False)
```

```typescript deletion_protection.ts theme={null}
import { NotteClient } from 'notte-sdk';

const client = new NotteClient();
const fn = client.NotteFunction({ function_id: functionId });

// Protect the function: deletes are refused until this is turned off
const { deletion_protected } = await fn.updateMetadata({ deletion_protected: true });
console.log(deletion_protected);

// Turning it off takes the key of a workspace admin or owner
const released = await fn.updateMetadata({ deletion_protected: false });
```

Any workspace member can turn protection on. Only a workspace admin or owner can turn it off, and an API key acts with its owner's role.

## Sharing Functions

### Change sharing for an existing function

Set `shared` on the metadata operation to enable or disable its public code/fork
link without creating a function or uploading code again:

* Python: `client.functions.metadata_update(function_id, shared=True)`.
* TypeScript: `await client.functions.metadataUpdate(functionId, { shared: true })`,
  or `await fn.updateMetadata({ shared: true })` for an existing function wrapper.
* HTTP: `PATCH /functions/{function_id}` with the JSON body `{"shared": true}`.

Use `False` in Python or `false` in HTTP/TypeScript to disable the fork link.
Omitting `shared`, or sending null, preserves the current setting. HTTP requires
an actual boolean, rather than the strings `"true"` or `"false"`.

```bash theme={null}
notte functions configure --function-id ID --shared
notte functions configure --function-id ID --shared=false
```

Sharing exposes source code, including literals embedded in it. Runs, results and
stored runtime secrets stay private. Sharing does not enable public execution of
the author's function. Disabling the link prevents new forks; copies already
forked into other workspaces remain usable. Share the URL
`<console origin>/fork/<function_id>` using the Console for the same environment.

### Create a public function

You can also choose sharing when creating a function:

```python make_public.py theme={null}
from notte_sdk import NotteClient

client = NotteClient()

# Deploy as shared
function = client.Function(
    path="my_function.py",
    name="Public Scraper",
    shared=True,  # Other users can view and fork it
)
```

**Shared Functions:**

* ✅ Others can view and fork
* ✅ Original remains under your control
* ❌ Others cannot modify your version

### Private Functions

Keep Functions private (default):

```python private_function.py theme={null}
from notte_sdk import NotteClient

client = NotteClient()

function = client.Function(
    path="my_function.py",
    name="Private Automation",
    shared=False,  # Private (default)
)
```

```typescript private_function.ts theme={null}
import { NotteClient } from 'notte-sdk';

const client = new NotteClient();

const fn = client.NotteFunction({
  path: 'my_function.py',
  name: 'Private Automation',
  shared: false, // Private (default)
});
```

## Best Practices

### 1. Version Your Functions

Update incrementally with clear changes:

```python version_backup.py theme={null}
from notte_sdk import NotteClient

client = NotteClient()

function = client.Function(function_id="func_abc123")

# Before major update, download current version
current_code = function.download()

# Save backup
with open(f"backups/function_v{function.response.latest_version}.py", "w") as f:
    f.write(current_code)

# Update function
function.update(path="new_version.py")
```

### 2. Monitor Function Health

Regular health checks:

```python function_health_check.py theme={null}
from notte_sdk import NotteClient

client = NotteClient()


def check_function_health(function_id: str):
    """Check recent run success rate."""
    runs = client.functions.list_runs(function_id, only_active=False)

    total = len(runs.items)
    failed = sum(1 for r in runs.items if r.status == "failed")

    success_rate = ((total - failed) / total * 100) if total > 0 else 0

    print(f"Success rate: {success_rate:.1f}%")
    print(f"Total runs: {total}")
    print(f"Failed runs: {failed}")

    return success_rate


# Monitor function
check_function_health("func_abc123")
```

### 3. Clean Up Old Runs

Archive or analyze old execution data:

```python cleanup_old_runs.py theme={null}
import json
from datetime import datetime, timedelta, timezone

from notte_sdk import NotteClient

client = NotteClient()


def archive_old_runs(function_id: str, days_old: int = 30):
    """Archive runs older than specified days."""
    # Most recent page of runs (up to 100), including finished ones
    runs = client.functions.list_runs(function_id, only_active=False, page_size=100)

    cutoff_date = datetime.now(timezone.utc) - timedelta(days=days_old)
    archive = []

    for run in runs.items:
        if run.created_at < cutoff_date:
            run_detail = client.functions.run_get_metadata(function_id, run.function_run_id)
            archive.append(
                {
                    "run_id": run.function_run_id,
                    "status": run.status,
                    "created_at": run.created_at.isoformat(),
                    "result": str(run_detail.result)[:100],  # First 100 chars
                }
            )

    # Save archive
    with open(f"archives/{function_id}_{datetime.now().date()}.json", "w") as f:
        json.dump(archive, f, indent=2)

    print(f"Archived {len(archive)} old runs")


archive_old_runs("function_abc123")
```

### 4. Document Changes

Keep change log for Function updates:

```python document_changes.py theme={null}
"""
Function: Data Scraper
Function ID: func_abc123

Version History:
- v1 (2024-01-15): Initial release
- v2 (2024-01-20): Added error handling
- v3 (2024-01-25): Improved scraping accuracy
- v4 (2024-02-01): Added retry logic
"""


def run(url: str):
    # Your function code
    pass
```

### 5. Test Before Production

Validate updates before deploying:

```python test_before_prod.py theme={null}
from notte_sdk import NotteClient


def validate_before_production():
    client = NotteClient()

    # Deploy the new version as a separate staging function first
    staging = client.Function(path="tested_function.py", name="my-function-staging")

    # Run it in the cloud against a test site
    test_result = staging.run(url="https://test-site.com")

    if test_result.status == "closed":
        print("Test passed, ready to update production")
        production = client.Function(function_id="func_abc123")
        production.update(path="tested_function.py")
    else:
        print(f"Test failed: {test_result.result}")

    # Remove the staging function once validated
    staging.delete(confirm=True)
```

## Troubleshooting

### Function Fails to Run

Check run details for errors:

```python troubleshoot_fails.py theme={null}
from notte_sdk import NotteClient

client = NotteClient()

run = client.functions.run_get_metadata("func_abc123", "run_xyz789")

if run.status == "failed":
    print(f"Error: {run.result}")

    # Replay the session the run opened, if any
    if run.session_id is not None:
        replay = client.sessions.replay(session_id=run.session_id)
        replay.download("debug_replay.mp4")
```

### Missing Secrets

Function Secrets reach your code as environment variables (see [Secrets](https://docs.notte.cc/features/functions/creating.md#secrets)). Check for them at the start of `run()`:

```python missing_env_vars.py theme={null}
import os


def run():
    # Names of the Function Secrets this code expects
    required_vars = ["API_KEY", "WEBHOOK_URL"]

    missing = [var for var in required_vars if not os.environ.get(var)]

    if missing:
        return {"error": f"Missing secrets: {', '.join(missing)}"}

    # Continue with automation
```

### High Failure Rate

Analyze failure patterns:

Set `function_id` (Python) or `functionId` (Node) to your Function's ID.
Include completed runs with `only_active=False` / `only_active: false` so failed runs appear.

```python high_failure_rate.py theme={null}
from notte_sdk import NotteClient

client = NotteClient()

runs = client.functions.list_runs(function_id, only_active=False)

failures = [r for r in runs.items if r.status == "failed"]

print(f"Failed runs: {len(failures)}/{len(runs.items)}")

# Analyze failure reasons
for run in failures[:5]:  # Last 5 failures
    run_detail = client.functions.run_get_metadata(function_id, run.function_run_id)
    print(f"Run {run.function_run_id}:")
    print(f"  Error: {run_detail.result}")
    print(f"  Time: {run.created_at}")
```

```typescript high_failure_rate.ts theme={null}
import { NotteClient } from 'notte-sdk';

const client = new NotteClient();

const fn = client.NotteFunction({ function_id: functionId });
const runs = await fn.runs({ only_active: false });
const failures = runs.items.filter(run => run.status === 'failed');

console.log(`Failed runs: ${failures.length}/${runs.items.length}`);

// Analyze failure reasons
for (const run of failures.slice(0, 5)) { // First 5 failures on this page
  const runDetail = await fn.getRun(run.function_run_id);
  console.log(`Run ${run.function_run_id}:`);
  console.log(`  Error: ${runDetail.result}`);
  console.log(`  Time: ${run.created_at}`);
}
```

## Next Steps

> [card] [Creating Functions](https://docs.notte.cc/features/functions/creating.md)
>
> Learn how to write Functions

> [card] [Invocations](https://docs.notte.cc/features/functions/invocations.md)
>
> Call Functions via API or SDK

> [card] [Schedules](https://docs.notte.cc/features/functions/schedules.md)
>
> Schedule Functions with cron

> [card] [Functions Concept](https://docs.notte.cc/concepts/functions.md)
>
> Back to Functions overview


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.