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

# Functions

> Serverless TypeScript that runs on Zavu Cloud and powers your agents — write code, run zavu deploy, your AI agent has new tools.

## Functions

A **Zavu Function** is a serverless TypeScript snippet that runs in Zavu Cloud and reacts to messaging events or AI agent tool calls. You write the code locally, run `zavu deploy`, and seconds later your agent is live with tools backed by real business logic — no servers, no Docker, no webhook receivers to maintain.

## What is a Zavu Function?

Think of a Function as the code-side counterpart to an AI Agent. Where an Agent decides *what* to say, a Function executes the actions the Agent needs — query a database, check inventory, book a reservation, call your own API.

* **Declare an agent in code** with `defineAgent` — config stays in sync with your repo.
* **Declare tools** with `defineTool` — handlers run inside Zavu Cloud when the LLM decides to call them.
* **React to events** with `defineFunction` — `message.inbound`, `broadcast.completed`, etc.
* **Auto-provisioned API key** — the function can call any Zavu API endpoint without you handling credentials.

<CodeGroup>
  ```ts Example: restaurant booking agent theme={null}
  import { defineAgent, defineTool } from "@zavu/functions"

  defineAgent({
    senderId: process.env.SENDER_ID!,
    name: "Bella",
    provider: "zavu",
    model: "openai/gpt-4o-mini",
    prompt: "You are Bella, host at La Pizzeria. Be brief.",
    channels: ["whatsapp"],
  })

  defineTool({
    name: "check_availability",
    description: "Get free reservation slots for a date and party size.",
    parameters: {
      type: "object",
      properties: {
        date: { type: "string" },
        partySize: { type: "number" },
      },
      required: ["date", "partySize"],
    },
    handler: async ({ date, partySize }) => {
      // your real booking logic here
      return { available: true, slots: ["19:00", "21:00"] }
    },
  })
  ```
</CodeGroup>

That's the entire integration. One file, `zavu deploy`, done.

## How it relates to AI Agents

| Need                                                 | Use                                                                    |
| ---------------------------------------------------- | ---------------------------------------------------------------------- |
| A no-code agent configured from the dashboard        | [AI Agents](/concepts/ai-agents)                                       |
| An agent with custom business logic in your own code | **Zavu Functions**                                                     |
| Both — start no-code, evolve to code                 | Start with AI Agents, migrate when you need real tools or custom flows |

Functions can fully manage an AI Agent: the `defineAgent` call creates and keeps the agent config in sync with your code on every deploy. The dashboard surfaces "managed by function" on these agents and disables manual edits to prevent drift.

## Mental model

```
+----------------+        +--------------------+        +-----------+
| WhatsApp user  | -----> | Zavu sender (WABA) | -----> | AI Agent  |
+----------------+        +--------------------+        +-----------+
                                                              |
                                                       (tool call)
                                                              v
                                            +-------------------------------+
                                            | Your Zavu Function            |
                                            |  defineTool(handler)          |
                                            +-------------------------------+
                                                              |
                                                       (return result)
                                                              v
                                                       Agent answers user
```

* **Fully managed runtime.** Each function runs in Zavu's serverless cloud. No consoles to log into — `zavu deploy` handles bundling, dependencies, and publishing.
* **Internal invocation.** When the agent calls a tool, we use signed internal invocations — your function is **not** publicly exposed. No HTTP, no HMAC secrets to rotate, no DDoS surface.
* **Native event binding.** Functions can also subscribe to Zavu events (`message.inbound`, `broadcast.completed`, etc.) via triggers.
* **Auto-provisioned credentials.** Every function gets a scoped `ZAVU_API_KEY` in its environment so it can call our SDK without you handling key distribution.

## Lifecycle

1. **`zavu fn init`** — scaffolds a project with `index.ts`, `package.json`, and a `.zavu/` config that links the local directory to a Function record in your Zavu project.
2. **`zavu fn secrets set KEY value`** — encrypts and stores secrets that will be injected as env vars at runtime.
3. **`zavu deploy`** — bundles your code + dependencies, ships them to Zavu Cloud, syncs the agent + tool declarations from your code into your project, and starts serving traffic. The dashboard reflects the new state immediately.
4. **`zavu fn logs --tail`** — streams runtime logs from invocations as they happen.
5. **`zavu fn versions`** — list deploys and roll back to any previous one.

## Pricing model

Functions are metered by **invocation units**. One unit equals one invocation of a 128 MB function on **arm64** (the default CPU architecture). Two multipliers compound:

### Memory multiplier

Higher memory configs cost proportionally more units per invocation:

| Memory  | Units per call |
| ------- | -------------- |
| 128 MB  | 1×             |
| 256 MB  | 2×             |
| 512 MB  | 4×             |
| 1024 MB | 8×             |

### CPU architecture multiplier

Functions default to **arm64** (AWS Graviton — \~20% cheaper compute). Switch to **x86\_64** only when an npm dependency requires it (native modules without arm64 prebuilds). x86 carries a 25% premium to cover the higher AWS Lambda pricing.

| Architecture      | Cost multiplier | When to use                                                                                |
| ----------------- | --------------- | ------------------------------------------------------------------------------------------ |
| `arm64` (default) | 1.00×           | Default. Works for all pure-TypeScript code and most native modules with modern prebuilds. |
| `x86_64`          | 1.25×           | When a critical npm package only ships x86 prebuilts (e.g. some image / crypto libs).      |

A 256 MB function on x86\_64 costs `2 × 1.25 = 2.5 units` per invocation.

Set the architecture via:

* **`package.json`**: `{ "zavu": { "architecture": "x86_64" } }` (versioned in git)
* **CLI flag**: `zavu deploy --arch x86_64`
* **Dashboard**: Function detail → Settings → CPU architecture

The change takes effect on the next deploy.

### Plan quotas

Each paid plan includes a generous monthly quota; overage is billed automatically on your next invoice via Stripe Meters.

| Plan     | Included units | Overage                                     |
| -------- | -------------- | ------------------------------------------- |
| Free     | 100k           | Hard cap — invocations blocked when reached |
| Hobby    | 1M             | \$5 / 1M units                              |
| Standard | 5M             | \$4 / 1M units                              |
| Growth   | 10M            | \$3 / 1M units                              |

### Examples

| Setup          | Invocations | Units consumed | Plan: overage at Hobby |
| -------------- | ----------- | -------------- | ---------------------- |
| 128 MB arm64   | 1.5M        | 1.5M           | \$2.50                 |
| 128 MB x86\_64 | 1.5M        | 1.875M         | \$4.38                 |
| 256 MB arm64   | 1.5M        | 3M             | \$10.00                |
| 256 MB x86\_64 | 1.5M        | 3.75M          | \$13.75                |

Cold start, network call, error — every invocation counts the same. The unit model is intentionally aligned with the underlying compute cost so you can predict overage from your code's memory + architecture profile.

## Generate Functions code with AI

Install [Zavu's Coding Agent Skills](/tools/coding-agent-skills) in your IDE
(Claude Code, Cursor, Copilot, and 40+ others) and your AI assistant will know
the full `defineAgent` / `defineTool` API, the `zavu` CLI, and the debugging
flow. Describe what you want — your agent writes the code.

```sh theme={null}
npx skills add zavudev/zavu-skills
```

The `functions` skill is loaded on-demand whenever you mention Functions,
tool handlers, or `zavu deploy`.

## Continue

* **[Quickstart](/guides/functions/quickstart)** — Full step-by-step from zero to live agent in 10 minutes.
* **[CLI reference](/guides/functions/cli)** — Every `zavu` command, flag by flag.
* **[Defining agents](/guides/functions/defining-agents)** — `defineAgent` API, providers, prompts, models.
* **[Defining tools](/guides/functions/defining-tools)** — `defineTool` API, schemas, handlers, error handling.
* **[Secrets](/guides/functions/secrets)** — Environment variables encrypted at rest.
* **[Triggers](/guides/functions/triggers)** — Listen to Zavu events from your function.
* **[Runtime versions](/guides/functions/runtime)** — How pinning works, when to upgrade.
* **[Advanced patterns](/guides/functions/advanced-patterns)** — Persistent state, observability, retries, costs.
* **[Examples](/guides/functions/examples/restaurant)** — Complete walkthroughs.
