# Beam > Beam provides CPU and GPU machines for agents, billed by the millisecond: persistent VMs that pause with their memory intact, sandboxes that boot in seconds, and GPU endpoints for inference. > ## Agent Instructions > Install the Beam CLI, sign in, and connect coding agents to the Beam MCP server with `curl -fsSL https://www.beam.cloud/install | sh`. To also create a VM, run `curl -fsSL https://www.beam.cloud/install | sh -s -- --vm`. > VMs are persistent Linux machines without GPUs. Defaults: 4 CPUs, 8 GiB of RAM, a 50 GiB disk, Ubuntu 24.04, and a browser desktop. A running VM accrues usage until you stop, pause, or remove it, or until an idle timeout puts it to sleep. > Stopping a VM keeps its disk and discards RAM and processes. Pausing keeps both, and resuming restores them. To pause after 5 idle minutes and wake on access, run `beam vm update NAME --ttl 300 --idle-action pause --auto-resume`. > Core VM commands: `beam vm new NAME`, `beam vm ssh NAME`, `beam vm sync NAME ./dir`, `beam vm exec NAME -- CMD`, `beam vm expose NAME PORT --protected`, `beam vm fork NAME NEW_NAME`, `beam vm pause NAME`, `beam vm stop NAME`, `beam vm rm NAME`. > For GPUs, use a sandbox or a deployed endpoint. Sandboxes are disposable environments that boot in seconds and fork from snapshots. > Current rates are at https://www.beam.cloud/pricing. # Building AI Agents Source: https://docs.beam.cloud/v2/agents/introduction Beam is launching a new type of agent framework that is stateful and has concurrency built-in. > [card] Other agent frameworks can't... > > • Multi-task \\ > > • Automatically synchronize state \\ > > • Run each task in an isolated environment \ > • Scale to 100s of GPUs > [card] Beam gives you everything you need > > • Sandboxed compute environments \\ > > • Concurrency \\ > > • Task management and queuing \\ > > • Edge deployment and autoscaling \\ > > • Authentication \ > • Lots of GPUs ## Introduction Today, most agent frameworks are based on graph DAGs. While useful for simple tasks, this limits you to performing one action at a time (i.e. using one tool at a time). Beam uses a new agentic concurrency model, based on [*petri nets*](https://en.wikipedia.org/wiki/Petri_net), which are capable of multi-tasking complex, multi-threaded workflows. By combining this agent framework with Beam's cloud compute, you can build powerful, parallelized applications. ![](https://mintcdn.com/slai-beam/vg5aTEbpFmupCYom/img/v2/bot-dashboard.png?fit=max\&auto=format\&n=vg5aTEbpFmupCYom\&q=85\&s=bf337c97968c883bc263713a9b75f8ba) ## Core Concepts Our agent framework has three important components: locations, transitions, and markers. For this example, suppose we're modeling an eCommerce store. * **Locations** -- these are specific *states* or *conditions* that hold tokens. For example, `in_shopping_cart` or `in_queue`. * **Transitions** -- events or actions that cause state changes. For example `place_order` or `accept_payment`. Each transition has: * **Inputs** -- the locations the data is consumed from. * **Outputs** -- the locations the data is sent. * **Markers** -- markers are *data types*. For example, `order_12345_red_shoes`. > [!TIP] > > Think of a Petri net as a factory assembly line, where parts (markers) move > between workstations (locations), and tasks (transitions) are performed when > all required parts are in place. ## Initial Setup Let's setup a simple `hello world` chatbot. This chatbot will respond to messages from a user. It will ask the user for their name, and attempt to update the status of their order. ### Pre-requisites * A free Beam account, and [Beam installed on your computer](/v2/getting-started/installation) * An [OpenAI API key](https://platform.openai.com/api-keys) ### Hello World We'll start by creating a `bot`, a `transition`, and initial state `markers`: ```python theme={null} from beam import Bot # Create the bot -- make sure to add your own OpenAI API key bot = Bot( model="gpt-4o", api_key="YOUR_OPENAI_API_KEY", locations=[], description="A simple bot to cancel orders.", ) ``` ## Managing State Now we'll add `locations` and `markers`, which represent *state*. ```python app.py {2,6-11,19-20} theme={null} from beam import Bot, BotContext, BotLocation from pydantic import BaseModel # Marker states for the bot class UserName(BaseModel): name: str class OrderStatus(BaseModel): message: str # Create the bot -- make sure to add your own OpenAI API key bot = Bot( model="gpt-4o", api_key="YOUR_OPENAI_API_KEY", locations=[ BotLocation(marker=UserName), BotLocation(marker=OrderStatus), ], description="A simple bot to cancel orders.", ) ``` ## Adding Transitions Let's add our first **transition**. A transition is a state change. It takes our `UserName` location and returns an `OrderStatus` location. ```python app.py {27-33} theme={null} from beam import Bot, BotContext, BotLocation from pydantic import BaseModel # Marker states for the bot class UserName(BaseModel): name: str class OrderStatus(BaseModel): message: str # Create the bot -- make sure to add your own OpenAI API key bot = Bot( model="gpt-4o", api_key="YOUR_OPENAI_API_KEY", locations=[ BotLocation(marker=UserName), BotLocation(marker=OrderStatus), ], description="A simple bot to cancel orders.", ) # This transition prompts the user for their name and cancels their orders @bot.transition( cpu=1, memory=128, inputs={UserName: 1}, outputs=[OrderStatus], description="Cancels a users order.", ) def handler(**inputs): ... # Add the handler implementation shown below. ``` ## Interacting with User Input Let's add basic logic in the transition. We'll accept a username, and update a dict with the user's order status. ### Adding Prompts We'll introduce a new concept, called `context`, which is a class that provides various convenience methods for your bot. ```python app.py {14-15, 37-46} theme={null} from beam import Bot, BotContext, BotLocation from pydantic import BaseModel # Marker states for the bot class UserName(BaseModel): name: str class OrderStatus(BaseModel): message: str # Hardcoded user data (mock database) USER_DATA = {"Alice": "processing", "Bob": "shipped"} # Create the bot -- make sure to add your own OpenAI API key bot = Bot( model="gpt-4o", api_key="YOUR_OPENAI_API_KEY", locations=[ BotLocation(marker=UserName), BotLocation(marker=OrderStatus), ], description="A simple bot to cancel orders.", ) # This transition prompts the user for their name and cancels their orders @bot.transition( cpu=1, memory=128, inputs={UserName: 1}, outputs=[OrderStatus], description="Cancels a users order.", ) def cancel_order(context: BotContext, inputs): # Get the name provided by the user user_name = inputs[UserName][0].name # Update the user's order status USER_DATA[user_name] = "cancelled" # Send a message in the chat context.say(f"Order cancelled for {user_name}") # Return a marker state return {OrderStatus: [OrderStatus(message="order_cancelled")]} ``` ### Human-in-the-loop We can also add a confirmation prompt, so that user input is required before the bot can proceed to the next step. Let's add the `confirm` flag to the transition: ```python app.py {48-51} theme={null} @bot.transition( cpu=1, memory=128, inputs={UserName: 1}, outputs=[OrderStatus], description="Cancels a users order.", confirm=True ) def handler(**inputs): ... # Add the handler implementation shown below. ``` The bot will only proceed if the user confirms the request. ### Adding Transitions Let's add a second transition, which will issue a refund to the user after they cancel their order. This transition will fire when an `OrderStatus` marker is created. ```python theme={null} class RefundStatus(BaseModel): message: str @bot.transition( cpu=1, memory=128, inputs={OrderStatus: 1}, outputs=[RefundStatus], description="Offers a refund to the user after cancelling their order.", expose=False, # The bot won't take this into account when asking the user for input ) def offer_refund(context: BotContext, inputs): # Process the refund (mock logic) refund_message = f"Your refund for the cancelled order has been processed. You should see it in your account within 3-5 business days." # Send a message in the chat context.say(refund_message) ``` You'll notice that we're not returning a marker, because this transition marks the end of our workflow. After this transition runs, there's no state left to update. ## Advanced Usage ### Controlling Bot Awareness Based on the [system prompt](https://github.com/beam-cloud/beta9/blob/main/pkg/abstractions/experimental/bot/prompt.yaml), the bot automatically knows about all the locations and transitions defined in the network. This means that the bot will understand its role based on the data you add to your transitions. However, you might not want the bot to know about certain transitions or locations! > [!TIP] > > If you want certain things hidden from the bot's context, you can pass > `expose=false` to locations and transitions. Think of hidden transitions as 'backstage actions' -- users can still interact with them, but the bot won't take it into account in its reasoning. ```python {7} theme={null} @bot.transition( cpu=1, memory=128, inputs={OrderStatus: 1}, outputs=[RefundStatus], description="Offers a refund to the user after cancelling their order.", expose=False, # This prevents the bot from using this transition in its reasoning ) def handler(**inputs): ... # Add the handler implementation shown below. ``` ### Using Context Commands We provide a number of helper commands using a class called `context`. Context variables can be used for prompting the user for input, creating blocking requests to the bot, and sending message to the user. ***Available Commands*** | Method | Description | | - | - | | `context.confirm()` | Pause a transition until a user says yes or no. | | `context.prompt()` | Send a blocking or non-blocking request to the model (e.g., "summarize these reviews"). You can pass an optional `wait_for_response=False` boolean to make this non-blocking. | | `context.remember()` | Add an arbitrary JSON-serializable object to the conversation memory. | | `context.say()` | Output text to the user's chat window. | | `context.send_file()` | Send a file to the user created during a transition. | | `context.get_file()` | Retrieve a file from the user during a transition. | ## Development Workflow ### Testing We'll start by running the bot from our shell, as a temporary development server. ```sh theme={null} $ beam serve app.py:bot ``` This command will spin up a container in the cloud for the bot `transition`, and create an interactive dialogue in your shell. ```sh theme={null} => Building image => Using cached image => Syncing files => Files synced => Invocation details websocat 'wss://979563f1-b569-4f2c-8113-dc6ebca007d1.app.beam.cloud' => Session started: 062a4f => Chat with your bot below... ``` You can interact with your bot by typing into the shell. In your shell, you'll see responses from the bot, as well as event logs from each transition that fires. ```sh theme={null} { "type": "agent_message", "value": "Hello! How can I assist you today? If you would like to cancel an order, please provide the user's name to get started.", "metadata": { "request_id": "b2f58de9-7c93-4eda-9a8d-fc42d4e40561", "session_id": "062a4f" } } # hi - please cancel alice's order # { "type": "agent_message", "value": "I've noted the request to cancel Alice's order. If there's anything else you need, just let me know!", "metadata": { "request_id": "93c0f077-b663-46a0-b110-d63376c8821f", "session_id": "062a4f" } } { "type": "transition_fired", "value": "cancel_order", "metadata": { "session_id": "062a4f", "task_id": "bf45f661-daaa-4d70-83f1-0479587fafe9", "transition_name": "cancel_order" } } { "type": "transition_started", "value": "cancel_order", "metadata": { "session_id": "062a4f", "task_id": "bf45f661-daaa-4d70-83f1-0479587fafe9", "transition_name": "cancel_order" } } { "type": "agent_message", "value": "\u2705 Order cancelled for alice", "metadata": { "session_id": "062a4f", "task_id": "bf45f661-daaa-4d70-83f1-0479587fafe9", "transition_name": "cancel_order" } } { "type": "transition_completed", "value": "cancel_order", "metadata": { "session_id": "062a4f", "task_id": "bf45f661-daaa-4d70-83f1-0479587fafe9", "transition_name": "cancel_order" } } ``` ### Deployment ``` $ beam deploy app.py:bot --name order-bot ``` You can login to the Beam Dashboard and use the web UI to chat with your bot, view the network graph, and view the event logs for each task. ![](https://mintcdn.com/slai-beam/vg5aTEbpFmupCYom/img/v2/bot-dashboard.png?fit=max\&auto=format\&n=vg5aTEbpFmupCYom\&q=85\&s=bf337c97968c883bc263713a9b75f8ba) ## Creating Public Chatbots You can also create sharable pages for your chatbot by adding `authorized=False` to your `bot`: ```python app.py {11} theme={null} from beam import Bot, BotContext, BotLocation bot = Bot( model="gpt-4o", api_key="YOUR_OPENAI_API_KEY", locations=[ BotLocation(marker=UserName), BotLocation(marker=OrderStatus), ], description="A simple bot to cancel orders.", authorized=False, ) ``` When deployed, you can access a public URL for your bot, which looks like this: ![](https://mintcdn.com/slai-beam/vg5aTEbpFmupCYom/img/v2/bot-chat.png?fit=max\&auto=format\&n=vg5aTEbpFmupCYom\&q=85\&s=17a81d3a2905083c80d30affb3249ccb) # Example: Research Assistant Source: https://docs.beam.cloud/v2/agents/synchronization Beam's agent framework is designed for concurrency and synchronization. In this example, we'll show how you can deploy an app that scrapes online product reviews. You can follow along with the tutorial in the video below. [YouTube video player](https://www.youtube.com/embed/TNcwqvCW2d0?si=uoErZUqp-ZSaQ1Bp) ## Why Beam? Beam's Petri Net framework is ideal for workflows that require concurrency and scalability. This app uses Beam to: * **Retrieve Google Shopping URLs** for a product name you provide to the bot. * **Scrape review pages** for those products. * **Summarize reviews** into a report. ## Pre-requisites You'll need three API keys to run the example below: * [Firecrawl API key](https://docs.firecrawl.dev/introduction) (free), used for scraping product pages * [SerpApi API key](https://serpapi.com/) (free for 100 searches a month), used to retrieve Google Shopping URLs * [OpenAI API Key](https://platform.openai.com/docs/quickstart) Set up your environment variables by adding these keys to a `.env` file in your project directory. ``` OPEN_AI_API_KEY=your_openai_api_key SERPAPI_API_KEY=your_serpapi_api_key FIRECRAWL_API_KEY=your_firecrawl_api_key ``` ## Setup ### Defining Locations Locations represent the states of data flowing through the network. In this app, we'll use three states: * **ProductName**: The product to search for (i.e. "headphones") * **URL**: URLs of product pages retrieved from Google Shopping * **ReviewPage**: Online product pages with customer reviews Define these locations in your code: ```python theme={null} from pydantic import BaseModel class ProductName(BaseModel): product_name: str class URL(BaseModel): url: str class ReviewPage(BaseModel): review_page: str ``` ### Create the Bot Let's setup the bot, which is what manages the workflow. Add your API keys and define the locations (states) it will manage. ```python theme={null} from beam import Bot, BotLocation bot = Bot( model="gpt-4o", api_key=OPEN_AI_API_KEY, locations=[ BotLocation(marker=ProductName), BotLocation(marker=URL, expose=False), BotLocation(marker=ReviewPage, expose=False), ], description="This bot will take a product category as input, search for reviews, and summarize them.", ) ``` ## Adding Transitions Transitions are events or actions in your bot, triggered by changes to the locations (state). ### Retrieve Product URLs The first transition takes a product category (e.g., "headphones") and uses SerpAPI to retrieve Google Shopping URLs for the product. ![](https://mintcdn.com/slai-beam/vg5aTEbpFmupCYom/img/v2/shopping.png?fit=max\&auto=format\&n=vg5aTEbpFmupCYom\&q=85\&s=c761f21b4809198d0142000375a3ce38) ```python theme={null} from beam import Image from serpapi import GoogleSearch @bot.transition( inputs={ProductName: 1}, outputs=[URL], description="Retrieve Google Shopping results for a product.", cpu=1, memory=128, image=Image(python_packages=["serpapi", "python-dotenv"]), ) def get_product_urls(context, inputs): product_name = inputs[ProductName][0].product_name params = { "engine": "google_shopping", "q": product_name, "api_key": SERPAPI_API_KEY, } search = GoogleSearch(params) results = search.get_dict() urls = results["shopping_results"][:3] return {URL: [URL(url=url["product_link"]) for url in urls]} ``` ### Scrape Review Pages The second transition scrapes review pages from each product URL using Firecrawl. ```python theme={null} from firecrawl import FirecrawlApp import json @bot.transition( inputs={URL: 1}, outputs=[ReviewPage], description="Scrape review pages for product URLs.", cpu=1, memory=128, image=Image(python_packages=["firecrawl-py", "python-dotenv"]), expose=False, ) def scrape_reviews(context, inputs): url = inputs[URL][0].url app = FirecrawlApp(api_key=FIRECRAWL_API_KEY) scrape_result = app.scrape_url(url, params={"formats": ["markdown"]}) return {ReviewPage: [ReviewPage(review_page=json.dumps(scrape_result))]} ``` ### Summarize Reviews The final transition summarizes reviews from all the scraped pages into a markdown file. Pay close attention to the `inputs` field below. **This transition will not begin running until 3 `ReviewPage` markers have been created from the previous transition.** ```python {2} theme={null} @bot.transition( inputs={ReviewPage: 3}, outputs=[], description="Summarize product reviews.", cpu=1, memory=128, image=Image(python_packages=["python-dotenv"]), expose=False, ) def summarize_reviews(context, inputs): all_review_pages = "\n".join([input.review_page for input in inputs[ReviewPage]]) prompt = f""" The following pages contain markdown reviews for products. Summarize the key takeaways, including 1-3 direct quotes from reviewers. Ensure the product name and URL are included: {all_review_pages} """ event = context.prompt(msg=prompt, timeout_seconds=30) summary = event.value file_path = "/tmp/product-reviews.md" with open(file_path, "w") as f: f.write(summary) context.say("Product reviews summarized successfully!") if context.confirm(description="Do you want a sharable link to the summary?"): context.send_file(path=file_path, description="Product Review Summary") ``` Once deployed, you'll be able to see the tasks in the dashboard, with the transition waiting until all `ReviewPage` markers have been emitted. ![](https://mintcdn.com/slai-beam/vg5aTEbpFmupCYom/img/v2/scrape-transition.png?fit=max\&auto=format\&n=vg5aTEbpFmupCYom\&q=85\&s=341c54fc226ca4a9ede54f6275c45969) ## Deploying the Bot ```sh theme={null} $ beam deploy app.py:bot --name product-review-bot ``` Deploying the bot gives you access to a dashboard, where you can interact with the bot using a Chat UI. ![](https://mintcdn.com/slai-beam/vg5aTEbpFmupCYom/img/v2/chat-ui.png?fit=max\&auto=format\&n=vg5aTEbpFmupCYom\&q=85\&s=7ac508624694cd49d3151dce0f941f9c) ## What's next? With the bot deployed, there are a few things you can try: ### Create a Public Chat Page You can create a public, sharable Chat Page for your bot by adding an `authorized=False` argument to the `bot`: ```python {6} theme={null} from beam import Bot, BotLocation bot = Bot( model="gpt-4o", api_key=OPEN_AI_API_KEY, authorized=False, locations=[ BotLocation(marker=ProductName), BotLocation(marker=URL, expose=False), BotLocation(marker=ReviewPage, expose=False), ], description="This bot will take a product category as input, search for reviews, and summarize them.", ) ``` When deployed, this gives you a sharable Chat UI. You can retrieve the URL to the Chat UI by clicking next to the "lock" icon. ![](https://mintcdn.com/slai-beam/vg5aTEbpFmupCYom/img/v2/public-url.png?fit=max\&auto=format\&n=vg5aTEbpFmupCYom\&q=85\&s=aa7d13920e03d79271014d3142c1ee8d) Here's what the Chat UI looks like: ![](https://mintcdn.com/slai-beam/vg5aTEbpFmupCYom/img/v2/chat-page.png?fit=max\&auto=format\&n=vg5aTEbpFmupCYom\&q=85\&s=3793cb07ce5b5a58e92bbb92aaf98bd8) ### Add Interactivity We provide a number of helper commands using a class called `context`. Context variables can be used for prompting the user for input, creating blocking requests to the bot, and sending message to the user. ***Available Commands*** | Method | Description | | - | - | | `context.confirm()` | Pause a transition until a user says yes or no. | | `context.prompt()` | Send a blocking or non-blocking request to the model (e.g., "summarize these reviews"). You can pass an optional `wait_for_response=False` boolean to make this non-blocking. | | `context.remember()` | Add an arbitrary JSON-serializable object to the conversation memory. | | `context.say()` | Output text to the user's chat window. | | `context.send_file()` | Send a file to the user from a transition. | | `context.get_file()` | Retrieve a file from the user during a transition. | ## View The Code You can see the full code for this example below. > [accordion] View The Code > > ```python theme={null} > from beam import Bot, BotContext, BotLocation, Image > from pydantic import BaseModel > > from dotenv import load_dotenv > import os > > load_dotenv() > > OPEN_AI_API_KEY = os.getenv("OPEN_AI_API_KEY") > SERPAPI_API_KEY = os.getenv("SERPAPI_API_KEY") > FIRECRAWL_API_KEY = os.getenv("FIRECRAWL_API_KEY") > > NUMBER_OF_PRODUCT_REVIEWS_TO_SUMMARIZE = 3 > > > # Define Locations (States) > class ProductName(BaseModel): > product_name: str > > > class URL(BaseModel): > url: str > > > class ReviewPage(BaseModel): > review_page: str > > > # Create the Bot > bot = Bot( > model="gpt-4o", > api_key=OPEN_AI_API_KEY, > locations=[ > BotLocation(marker=ProductName), > BotLocation(marker=URL, expose=False), > BotLocation(marker=ReviewPage, expose=False), > ], > description="This bot will take a product category as input (i.e. 'headphones') and search Google shopping for those products, lookup reviews for each of them, and then summarize the reviews of all products in a summary.", > ) > > > # Transition 1: Retrieve 3 Google shopping URLs for each product > @bot.transition( > inputs={ProductName: 1}, > outputs=[URL], > description="Takes a product name and retrieves 5 Google shopping results", > cpu=1, > memory=128, > image=Image(python_packages=["serpapi", "google-search-results", "python-dotenv"]), > ) > def get_product_urls(context: BotContext, inputs): > product_name = inputs[ProductName][0].product_name > > from serpapi import GoogleSearch > > params = { > "engine": "google_shopping", > "q": product_name, > "api_key": SERPAPI_API_KEY, > } > > search = GoogleSearch(params) > results = search.get_dict() > urls = results["shopping_results"][:NUMBER_OF_PRODUCT_REVIEWS_TO_SUMMARIZE] > > # Return a product url > return {URL: [URL(url=url["product_link"]) for url in urls]} > > > # Transition 2: Scrape review page > @bot.transition( > inputs={URL: 1}, > outputs=[ReviewPage], > description="Scrapes the review page for each URL provided.", > cpu=1, > memory=128, > image=Image(python_packages=["firecrawl-py", "python-dotenv"]), > expose=False, > ) > def scrape_reviews(context: BotContext, inputs): > url = inputs[URL][0].url > > import json > > from firecrawl import FirecrawlApp > > app = FirecrawlApp(api_key=FIRECRAWL_API_KEY) > > # Scrape reviews from the product page > scrape_result = app.scrape_url(url, params={"formats": ["markdown"]}) > print(scrape_result) > > return {ReviewPage: [ReviewPage(review_page=json.dumps(scrape_result))]} > > > # Transition 3: Summarize the product reviews > @bot.transition( > inputs={ReviewPage: NUMBER_OF_PRODUCT_REVIEWS_TO_SUMMARIZE}, > outputs=[], > description="Summarizes the reviews.", > cpu=1, > memory=128, > image=Image().add_python_packages(["python-dotenv"]), > expose=False, > ) > def summarize_reviews(context: BotContext, inputs): > try: > all_review_pages = "\n".join( > [input.review_page for input in inputs[ReviewPage]] > ) > > print(all_review_pages) > > prompt = f""" > The following page contains markdown with a review for a product. > Please highlight the key takeaways from all the reviews, > and include 1-3 direct quotes from reviewers to support your points. > In each quote, make sure to cite the name of the reviewer (if available). > Make sure to include the name of the product, and a URL to buy it, in your response: > {all_review_pages} > """ > > event = context.prompt( > msg=prompt, > timeout_seconds=30, > ) > > context.say("I've summarized product reviews like so: " + event.value) > > file_path = "/tmp/product-reviews.md" > with open(file_path, "w") as f: > f.write(event.value) > > if context.confirm(description="Do you want a sharable link to the summary?"): > context.send_file(path=file_path, description="Summary of product reviews") > > except AttributeError: > context.say("Review not found.") > > ``` # Managed Databases Source: https://docs.beam.cloud/v2/data/databases Create Postgres, Redis, MySQL, and MongoDB services and connect your apps You can run Postgres, Redis, MySQL, or MongoDB on Beam. Each database includes a durable disk, generated credentials, and a TLS connection. | CLI kind | Engine | Default disk | Connection variable | | - | - | - | - | | `postgres` | Postgres 16 | 10Gi | `DATABASE_URL` | | `redis` | Redis 7 | 5Gi | `REDIS_URL` | | `mysql` | MySQL 8 | 10Gi | `DATABASE_URL` | | `mongo` | MongoDB 7 | 10Gi | `DATABASE_URL` | ## Create a Database ```bash theme={null} beam db postgres create web-db beam db redis create cache beam db mysql create analytics-db beam db mongo create documents-db beam db list ``` Each command creates a separate database with 1 CPU and 512 MB of memory. Names must be unique in your workspace. Use `--cpu`, `--memory`, `--database`, or `--username` to customize it. To supply a password, use `--password-from-env VARIABLE_NAME` or `--password-stdin`. Databases are also available in the dashboard and through MCP's `create_database` tool. ## Connect an App Pass the database URL as an [environment reference](/v2/hosting/references): ```bash theme={null} beam deploy --dockerfile Dockerfile --name web --port 8000 \ --env DATABASE_URL='${{db.web-db.DATABASE_URL}}' \ --env REDIS_URL='${{db.cache.REDIS_URL}}' ``` Python apps accept the same references in `env`: ```python theme={null} from beam import function @function(env={"DATABASE_URL": "${{db.web-db.DATABASE_URL}}"}) def inspect_configuration(): import os return {"database_configured": bool(os.environ.get("DATABASE_URL"))} ``` For an existing app, edit its environment variables in the dashboard or use MCP's `connect_services`. Both deploy a new version. ## Connect from Your Machine Print a connection command for Postgres or Redis: ```bash theme={null} beam db postgres connect web-db --psql beam db redis connect cache --redis-cli ``` Run the printed command with `psql` or `redis-cli` installed. The output contains credentials. For other clients, use `beam db KIND credentials NAME`. Redis also supports `connect --node-redis` and `--ioredis` for TLS connection examples. ## Serverless or Always On Databases shut down after 300 idle seconds by default. To avoid cold starts, keep one replica running: ```bash theme={null} beam db postgres scale web-db --always-on beam db postgres scale web-db --serverless beam db postgres scale web-db --cpu 2 --memory 2Gi ``` Use `--min-replicas 1` at creation for always-on mode. Each database has one writable replica; clients should reconnect after restarts or resource changes. ## Credentials and Lifecycle ```bash theme={null} beam db postgres status web-db beam logs web-db --since 30m beam db postgres rotate web-db ``` Rotation restarts the database and apps using its generated secrets. Update any connection strings you copied manually. `beam db postgres delete web-db` deletes the service and credentials, but **keeps the durable disk**. Use `beam disk list` to find it. See [disk snapshots](/v2/data/durable-disks#snapshots) for backups. # Durable Disks Source: https://docs.beam.cloud/v2/data/durable-disks Fast, node-local persistent storage for stateful workloads Durable disks give a container its own persistent storage on the local disk of the machine it runs on. Reads and writes go straight to local storage, and the contents survive across container restarts and redeployments. Use a durable disk when one process owns the data and needs fast, POSIX-complete access to it: a Postgres or Redis instance, a SQLite database, a vector index, a build cache, or a message queue. > [!TIP] > > If several containers need to read and write the same files at the same time, use a [Volume](/v2/data/volume) instead. Volumes are shared, distributed storage. Disks are attached to one running container at a time. > [!NOTE] > > Storage is not billed yet. Planned pricing is **\$0.0001 per GB-hour of data stored**, with no free allowance. > > This will use the same usage credits as compute and cover retained VM disk, volume, and snapshot data, including while compute is stopped. Empty disk capacity, shared base images, and internal copies are excluded. 1 GB = 1 billion bytes. ## Choosing Between Storage Types | | Volumes | Cloud Buckets | Durable Disks | | - | - | - | - | | Backed by | Beam's distributed file system | Your S3-compatible bucket | Local SSD on the worker node, snapshotted to object storage | | Shared between containers | Yes | Yes | One writer at a time (any number of read-only mounts) | | Best for | Model weights, datasets, shared outputs | Data you already keep in S3 | Databases, caches, and other single-writer state | | Consistency | Visibility is subject to filesystem caching | Depends on the provider; no appends | Local disk semantics inside the container | ## Attaching a Disk Declare a `DurableDisk` with a name, a size, and the path where it should appear inside the container, then pass it to your app with the `disks` parameter. ```python theme={null} from beam import DurableDisk, function disk = DurableDisk(name="app-data", size="10Gi", mount_path="/data") @function(cpu=0.25, memory=128, disks=[disk]) def append_and_read(): with open("/data/runs.log", "a") as f: f.write("container ran\n") with open("/data/runs.log") as f: return f.read() if __name__ == "__main__": print(append_and_read.remote()) ``` Run it, wait for the container to exit, and run it again. The second run returns two lines: the first one was written by a container that no longer exists. The `disks` parameter is accepted by [`Pod`](/v2/pod/web-service), [`function`](/v2/function/running-functions), [`endpoint`](/v2/endpoint/overview), [`task_queue`](/v2/task-queue/running-tasks), and [`Sandbox`](/v2/sandbox/overview). If a disk with that name does not exist in your workspace yet, Beam creates it the first time you run or deploy the app. You can also create disks ahead of time from the [CLI](#cli-management-commands). ### Running a Database on a Disk Use [managed databases](/v2/data/databases) for Postgres, Redis, MySQL, or MongoDB with generated credentials and an attached durable disk: ```bash theme={null} beam db postgres create app-db beam db postgres connect app-db --psql ``` For a custom stateful service, mount a disk in a [Service or Pod](/v2/hosting/containers) and configure the database's own authentication before exposing it. ### Parameters **name** `string` *required* The name of the disk. Names are unique within your workspace, so two apps that declare the same name share the same disk. **size** `string` *required* The declared size of the disk, for example `"10Gi"` or `"500Mi"`. The size is recorded on the disk and shown in the CLI; it is not changed by redeclaring the disk with a different value. **mount\_path** `string` *required* The absolute path where the disk is mounted inside the container. A disk without a mount path is not attached. **filesystem** `string` (default: ext4) The filesystem requested when creating the disk. Its effect depends on the storage driver. **read\_only** `boolean` (default: False) Mount the disk read-only. Read-only disks can be attached to any number of containers at once. See [Read-Only Disks](#read-only-disks). ## Snapshots When a container starts, Beam reuses its disk on the same node or restores the latest snapshot on a new node. You can list the snapshots of a disk with the CLI: ```sh theme={null} beam disk snapshots redis-data ``` ``` Disk Name Status Format Generation Logical Size Stored Size Created At ─────────────────────────────────────────────────────────────────────────────────────────────────────────── redis-data available redis.aof.v1 1783980128619331915 234.00 B 234.00 B Jul 13 2026 redis-data available redis.aof.v1 1783979768654042369 340.00 B 340.00 B Jul 13 2026 2 snapshots ``` * **Generation** is a timestamp assigned when the snapshot is taken. The highest generation is the most recent snapshot and is the one used for restores. * **Logical Size** is the total size of the files in the snapshot. **Stored Size** is the size of the object storage chunks the snapshot references. * **Format** describes how the directory was captured. `dir.v1` is the general format. Beam's managed databases use `postgres.wal.v1` and `redis.aof.v1`, which recognize Postgres write-ahead log segments and Redis append-only files: when one of those files has grown since the last snapshot, only the newly appended tail is uploaded. Snapshots are kept until you delete them. Deleting a disk does not delete its snapshots. ## Read-Only Disks Only one container can have a writable mount of a given disk at a time. Deploying an app that mounts a writable disk with an autoscaler that allows more than one container is rejected: ``` ✗ writable durable disks support one container; set max containers to 1 or mark the disk read_only ``` Set `read_only=True` to mount a disk without write access. Read-only mounts are exempt from the single-writer rule, so you can attach the same disk to a horizontally scaled endpoint. A typical pattern is one writer that prepares data, such as a nightly job that builds an index, and many readers that serve it: ```python theme={null} from beam import DurableDisk, QueueDepthAutoscaler, endpoint index = DurableDisk(name="search-index", size="20Gi", mount_path="/index", read_only=True) @endpoint( name="search", disks=[index], autoscaler=QueueDepthAutoscaler(max_containers=10), ) def search(query: str): ... ``` Readers start from the disk's latest snapshot, so a new snapshot only reaches them the next time their containers start. ## Limits and Caveats * **One writer.** A writable disk can be mounted by one container at a time. Scale-out requires `read_only=True`. * **Durability follows snapshot publication.** Changes since the last successfully published snapshot can be lost if the worker is lost. Inspect snapshot status and lifecycle errors. * **Size is fixed at creation.** Declaring an existing disk with a different `size` returns the existing disk unchanged. * **Deleting is soft.** `beam disk delete` removes the disk from your workspace but leaves its snapshots in place. Apps that still reference the name will recreate the disk record and, on their next start, restore from the latest snapshot. * **Mount path is required.** A `DurableDisk` without a `mount_path` is ignored. * **Leave the marker file alone.** Every disk contains a small `.beta9-durable-disk` file at its root that Beam uses to track snapshot state. ## Managed Databases Beam's managed Postgres, Redis, MySQL, and MongoDB services are built on durable disks. `beam db postgres create ` deploys a Postgres container with a `-data` disk mounted at `/var/lib/postgresql/data`, and `beam db redis create ` does the same with a disk at `/data`. The disks show up in `beam disk list` alongside any you create yourself. ```sh theme={null} beam db postgres create mydb beam db postgres connect mydb --psql ``` ## CLI Management Commands ### List Disks ```sh theme={null} beam disk list ``` ``` Name Size Filesystem Mount Path Created At Workspace Name ─────────────────────────────────────────────────────────────────────────────── redis-data 5Gi ext4 /data Jul 13 2026 85cfa7 app-data 10Gi ext4 /data Sep 13 2026 85cfa7 2 disks ``` Add `--format json` to get the full record, including the disk `id` and `driver`. ### Create a Disk ```sh theme={null} beam disk create [DISK-NAME] --size 10Gi --mount-path /data ``` `--size` defaults to `10Gi`. `--mount-path` sets the disk's default mount path, which is shown in `beam disk list`; the `mount_path` you set in code is what determines where the disk is mounted. If a disk with that name already exists, the command returns it unchanged. ### List Snapshots ```sh theme={null} beam disk snapshots [DISK-NAME] ``` Omit the name to list snapshots for every disk in the workspace. ### Delete a Disk ```sh theme={null} beam disk delete [DISK-NAME] ``` ``` Any apps or services (functions, endpoints, databases, etc) that refer to this disk should be updated before it is deleted. Are you sure? [y/N]: y ✓ Deleted disk: app-data ``` Pass `-y` to skip the confirmation. # Mounting S3 Buckets Source: https://docs.beam.cloud/v2/data/external-storage Attach S3 buckets to your apps Beam allows you to mount your own S3 buckets to your apps. Buckets are mounted using AWS's [mountpoint-s3](https://github.com/awslabs/mountpoint-s3). For an S3-compatible provider, configure its endpoint, region, credentials, and path-style requirements. Compatibility depends on the provider and the operations your application uses. Mountpoint is optimized for reading large files with high throughput and writing new files from a single client at a time. It does not provide full POSIX compliance. For instance, it does not support appending to files. > [!TIP] > > Cloud buckets allow you to expose your own S3-compatible storage as a file > system. ### Mounting an S3 Bucket External S3 buckets are special cases of the [volume abstraction](/v2/data/volume) with some extra configuration. To connect your bucket to your app, you need to provide the following: 1. The bucket name 2. An AWS access key 3. An AWS secret key 4. An S3 endpoint (if you're using a non-AWS S3-compatible provider) These will need to have permissions to read, write, and list objects in the bucket. Within AWS, you can use [IAM policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html) to control these permissions. Other S3-compatible providers (like Cloudflare R2 and Tigris) often provide these keys when you sign up for their service. You will need to store the access key and secret key in Beam's [secret manager](/v2/environment/secrets). You can do this using the Beam CLI: ```bash theme={null} beam secret create S3_KEY "your-access-key" beam secret create S3_SECRET "your-secret-key" ``` When a request is received to start the container, Beam looks up these secrets and uses them to mount the bucket. This means that you can use any names you like for the secrets. > [!WARNING] > > The secrets' names must match the values you enter in the `CloudBucketConfig`. The endpoint is optional. If you're using AWS S3, you can omit it, but if you're using a non-AWS S3-compatible provider, you will need to provide it. ```python theme={null} from beam import CloudBucket, CloudBucketConfig, function mount_path = "./weights" weights = CloudBucket( name="weights", mount_path=mount_path, config=CloudBucketConfig( access_key="S3_KEY", secret_key="S3_SECRET", ), ) @function(volumes=[weights]) def sandbox(): import os import uuid # Write to the bucket. file_name = f"{uuid.uuid4()}.txt" file_path = os.path.join(weights.mount_path, file_name) try: with open(file_path, "w") as f: f.write("hello world") except Exception as e: print(e) # Read from the bucket. with open(file_path, "r") as f: print(f.read()) if __name__ == "__main__": sandbox.remote() ``` > [!WARNING] > > The `name` field in the `CloudBucket` constructor must be the name of the > bucket you created in the cloud provider. ### Read Only Buckets You can mount your bucket as read only by setting the `read_only` flag to `True`. This will prevent any writes to the bucket. ```python theme={null} weights = CloudBucket( name="weights", mount_path="./weights", config=CloudBucketConfig( access_key="S3_KEY", secret_key="S3_SECRET", read_only=True, ), ) ``` ### Specifying a region You can specify a region for your bucket by setting the `region` field in the `CloudBucketConfig`. This option can be important when mounting AWS buckets. From mountpoint's [documentation](https://github.com/awslabs/mountpoint-s3/blob/main/doc/CONFIGURATION.md#region-detection): > Amazon S3 buckets are associated with a single AWS Region. Mountpoint attempts to automatically detect the region for your S3 bucket at startup time and directs all S3 requests to that region. However, in some scenarios like cross-region mount with a directory bucket, this region detection may fail, preventing your bucket from being mounted and displaying Access Denied or No Such Bucket errors. ```python theme={null} weights = CloudBucket( name="weights", mount_path="./weights", config=CloudBucketConfig( access_key="S3_KEY", secret_key="S3_SECRET", region="us-east-1", ), ) ``` ### Egress Fees If your bucket is in a different region than your Beam container, you might get charged egress fees by your cloud provider. You can read more about AWS S3 egress fees [here](https://aws.amazon.com/s3/pricing/). Check your storage provider's current transfer and request pricing before selecting a region. # Ephemeral Files and Images Source: https://docs.beam.cloud/v2/data/output Storing ephemeral files for images, audio files, and more. You may want to save data produced by your tasks. Beam provides an abstraction called `Output`, which allows you to save files or directories and generate public URLs to access them. ## Saving Files To save an `Output`, you can write any filetype to Beam's `/tmp` directory. Here's what your code might look like: ```python theme={null} from beam import function, Output @function() def save_output(): # File is saved to /tmp directory file_name = "/tmp/my_output.txt" # Write to new text file with open(file_name, "w") as f: f.write("This is an output, a glorious text file.") # Save output output_file = Output(path=file_name) output_file.save() # Generate and return a public URL public_url = output_file.public_url(expires=400) return {"output_url": public_url} ``` ### Directories You can also create public URLs for directories, by passing in a directory path: ```python theme={null} # Generate a public URL for a directory file_path = "/tmp/waveforms" output = Output(path=file_path) output.save() # Returns https://app.beam.cloud/output/id/abe0c95a-2cd1-40b3-bace-9225f2c79c6d output_url = output.public_url() ``` ### PIL Images If your app uses PIL, `Output` includes a wrapper around PIL to simplify the process of generating a public URL for the PIL image file: ```python theme={null} # Save a PIL image image = pipe(...) # Persist the PIL image to an Output output = Output.from_pil_image(image).save() ``` Here's a full example: ```python theme={null} from beam import Image as BeamImage, Output, function @function( image=BeamImage( python_packages=[ "pillow", ], ), ) def save_image(): from PIL import Image as PILImage # Generate PIL image pil_image = PILImage.new( "RGB", (100, 100), color="white" ) # Creating a 100x100 white image # Save image file output = Output.from_pil_image(pil_image) output.save() # Retrieve pre-signed URL for output file url = output.public_url(expires=400) print(url) # Print other details about the output print(f"Output ID: {output.id}") print(f"Output Path: {output.path}") print(f"Output Stats: {output.stat()}") print(f"Output Exists: {output.exists()}") return {"image": url} if __name__ == "__main__": save_image() ``` When you run this function, it will return a pre-signed URL to the image: ```bash theme={null} https://app.beam.cloud/output/id/abe0c95a-2cd1-40b3-bace-9225f2c79c6d ``` ## Generating Public URLs Your app might return files from the API, such as images or MP3s. You can use `Output` to generate a public URL to access the content. ![](https://mintcdn.com/slai-beam/vg5aTEbpFmupCYom/img/v2/output-graphic.png?fit=max\&auto=format\&n=vg5aTEbpFmupCYom\&q=85\&s=93bf6bd0d3dd58537935d18e43ee81ab) ### Expiring Public URLs You can pass an optional `expires` parameter to `output.public_url` to control how long to persist the file before it is deleted. The longest allowed value is `604800` seconds (7 days). Longer values, including `-1`, can produce a URL that returns a 400 error when opened. > [!NOTE] > > By default, public URLs are automatically deleted after 1 hour. ```python theme={null} # Delete public URL after 5 minutes output.public_url(expires=300) ``` # Distributed Storage Volumes Source: https://docs.beam.cloud/v2/data/volume Attach distributed storage volumes to your apps Beam allows you to create highly-available storage volumes that can be used across tasks. You might use volumes for things like storing model weights or large datasets. > [!TIP] > > Beam Volumes are mounted into containers and provide a shared filesystem interface for datasets, model caches, and outputs. Choose a [durable disk](/v2/data/durable-disks) for single-writer database state, or a [cloud bucket](/v2/data/external-storage) for storage you already manage. > [!NOTE] > > Storage is not billed yet. Planned pricing is **\$0.0001 per GB-hour of data stored**, with no free allowance. > > This will use the same usage credits as compute and cover retained VM disk, volume, and snapshot data, including while compute is stopped. Empty disk capacity, shared base images, and internal copies are excluded. 1 GB = 1 billion bytes. ## How to Write Files in Beam Containers There are two use-cases for saving files: *persistent* files, that you want to access between tasks, and *temporary* files that will be deleted when your container spins down. 1. **Persisting Files**: write to a volume. 2. **Temporary Files**: temporary files can be written to the `/tmp` directory in your Beam container, for example you could save an image to `/tmp/myimage.png`. ## Reading and Writing to Volumes You can read and write to your Volume like any ordinary Python file: ```python theme={null} from beam import function, Volume VOLUME_PATH = "./model_weights" @function( volumes=[Volume(name="model-weights", mount_path=VOLUME_PATH)], ) def access_files(): # Write files to a volume with open(f"{VOLUME_PATH}/somefile.txt", "w") as f: f.write("This is being written to a file in the volume") # Read files from a volume with open(f"{VOLUME_PATH}/somefile.txt", "r") as f: print(f.readlines()) if __name__ == "__main__": access_files.remote() ``` > [!WARNING] > > Changes to a volume may take time to appear in other containers. > [!NOTE] > > Running a database or another service where a single process owns its data? > A [durable disk](/v2/data/durable-disks) gives one container fast, node-local > storage that persists across restarts. To run this code, run `python [filename].py`. You'll see it print the text we just wrote to the file. ``` (.venv) $ python reading_and_writing_data.py => Building image => Using cached image => Syncing files Reading .beamignore file Collecting files from /Users/beta9/beam/examples/06_volume => Files synced => Running function: ['This is being written to a file in the volume'] => Function complete ``` ## Creating a Volume Volumes can be attached anything you run on Beam. > [!NOTE] > > By default, Volumes are scoped to a workspace and can be shared by its apps. ```python theme={null} from beam import function, Volume VOLUME_PATH = "./model_weights" @function( volumes=[Volume(name="model-weights", mount_path=VOLUME_PATH)], ) def load_model(): from transformers import AutoModel # Load model from cloud storage cache AutoModel.from_pretrained(VOLUME_PATH) ``` If you add a volume to your app, it will be created automatically. You can also create volumes manually in the CLI, by using: ```sh theme={null} $ beam volume create my-volume Name Created At Updated At Workspace Name ─────────────────────────────────────────────────────── my-volume just now just now f6fa28 ``` ## Uploading Data You can upload files with the CLI using the `beam cp` command. ```sh theme={null} beam cp [local-file] beam://[volume-name] ``` ### Files ```bash theme={null} beam cp file.txt beam://myvol/ # ./file.txt => beam://myvol/file.txt beam cp file.txt beam://myvol/file.txt # ./file.txt => beam://myvol/file.txt beam cp file.txt beam://myvol/file.new # ./file.txt => beam://myvol/file.new beam cp file.txt beam://myvol/hello # ./file.txt => beam://myvol/hello.txt (keeps the extension) ``` ### Directories ```bash theme={null} beam cp mydir beam://myvol # ./mydir/file.txt => beam://myvol/file.txt beam cp mydir beam://myvol/mydir # ./mydir/file.txt => beam://myvol/mydir/file.txt beam cp mydir beam://myvol/newdir # ./mydir/file.txt => beam://myvol/newdir/file.txt ``` ## Downloading Data ### Files ```bash theme={null} beam cp beam://myvol/file.txt . # beam://myvol/file.txt => ./file.txt beam cp beam://myvol/file.txt file.new # beam://myvol/file.txt => ./file.new ``` ### Directories ```bash theme={null} beam cp beam://myvol/mydir . # beam://myvol/mydir/file.txt => ./file.txt ``` ## CLI Management Commands ### Create a Volume ```bash theme={null} beam volume create [VOLUME-NAME] ``` ```bash theme={null} $ beam volume create weights Name Created At Updated At Workspace Name ─────────────────────────────────────────────────────── weights May 07 2024 May 07 2024 cf2db0 ``` ### Delete a Volume ```bash theme={null} beam volume delete [VOLUME-NAME] ``` ```bash theme={null} $ beam volume delete model-weights Any apps (functions, endpoints, task queue, etc) that refer to this volume should be updated before it is deleted. Are you sure? (y/n) [n]: y Deleted volume model-weights ``` ### List Volumes ```bash theme={null} beam volume list ``` ```bash theme={null} $ beam volume list Name Size Created At Updated At Workspace Name ───────────────────────────────────────────────────────────────────────────────────── weights 240.23 MiB 2 days ago 2 days ago cf2db0 1 volumes | 240.23 MiB used ``` ### List Volume Contents ```bash theme={null} beam ls [VOLUME-NAME] ``` ```bash theme={null} $ beam ls weights Name Size Modified Time IsDir ────────────────────────────────────────────────────────────────── .locks 0.00 B 29 minutes ago Yes models--facebook--opt-125m 240.23 MiB 28 minutes ago Yes 2 items | 240.23 MiB used ``` ### Copy Files to Volumes ```bash theme={null} beam cp [LOCAL-PATH] beam://[VOLUME-NAME] ``` ```bash theme={null} $ beam cp my-file beam://my-volume [beam://my-volume/my-file] ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 10.0/10.0 MiB 1.29 MiB/s 0:00:07 ``` ### Move Files in Volumes ```bash theme={null} beam mv [SOURCE] [DEST] ``` ```bash theme={null} $ beam mv my-volume/file.txt my-volume/files/text-files Moved file.txt to files/text-files/file.txt ``` ### Remove Files from Volumes ```bash theme={null} beam rm [FILE] ``` ```bash theme={null} => weights/app.py (1 object deleted) app.py ``` # Hosted Model Inference Source: https://docs.beam.cloud/v2/endpoint/hosted-models Discover and call models from the Endpoints catalog Use hosted models from the dashboard's **Endpoints** catalog. ## Discover Models ```bash theme={null} curl --fail-with-body https://app.beam.cloud/v1/models \ -H "Authorization: Bearer $BEAM_TOKEN" ``` The catalog is public. Include a token to see models available to your workspace. ## Call a Chat Model Install the OpenAI Python client and set `BEAM_MODEL` to a chat model ID from the catalog: ```python theme={null} import os from openai import OpenAI client = OpenAI( api_key=os.environ["BEAM_TOKEN"], base_url="https://app.beam.cloud/v1", ) response = client.chat.completions.create( model=os.environ["BEAM_MODEL"], messages=[{"role": "user", "content": "Explain what a container is in one sentence."}], ) print(response.choices[0].message.content) ``` Pass `stream=True` for streaming responses. Supported options vary by model. ## Other Model Types Use `/v1/embeddings` for embeddings or `/v1/models/{model-id}/invoke` for models with custom schemas. The model's catalog page includes request examples, image routes, and pricing. Inference requires a workspace token and credits for prepaid workspaces. Keep the token on your server. To deploy your own model, use an [endpoint](/v2/endpoint/overview) or [container](/v2/hosting/containers). # Keeping Containers Warm Source: https://docs.beam.cloud/v2/endpoint/keep-warm Control how long your apps stay running before shutting down. By default, Beam is serverless, which means your applications will shut off automatically when they're not being used. ## Configuring Keep Warm You can control how long your containers are kept alive by using the `keep_warm_seconds` flag in your deployment trigger. For example, by adding a `keep_warm_seconds=300` argument to an endpoint, an idle container remains warm for 5 minutes after activity before it can scale down: ```python theme={null} from beam import endpoint # Container stays alive for 5 min before shutting down automatically @endpoint(keep_warm_seconds=300) def handler(): return {} ``` > [!WARNING] > > When `keep_warm_seconds` is set in your deployment, it will count as billable > usage. ## Setting Always-On Containers > [!NOTE] > > Any running containers count towards billable usage. Take care to avoid > setting `min_containers` unless you're comfortable paying for usage 24/7. You can configure the number of containers running at baseline using the `min_containers` field. By setting `min_containers=1`, the autoscaler maintains a target of at least one running container while the deployment is active. > [!WARNING] > > After redeploying, stop any older versions you no longer need. Your > [rollout strategy](/v2/hosting/deployments) determines whether they stop automatically. ```python theme={null} from beam import endpoint, QueueDepthAutoscaler @endpoint( autoscaler=QueueDepthAutoscaler( min_containers=1, max_containers=3, tasks_per_container=1 ), ) def handler(): return {"success": "true"} ``` ## Pre-Warming Your Container You can pre-warm your containers by adding `/warmup` to the end of your deployment URL: ```sh theme={null} curl -X POST 'https://hello-world-a4bdc39-v1.app.beam.cloud/warmup' \ -H 'Authorization: Bearer [YOUR_TOKEN]' ``` When invoked, this endpoint will send a request to the container to warm-up. Endpoint, ASGI, and task-queue deployments support the warmup route. This is not a universal route for arbitrary Pod web servers. The gateway also exposes these path forms: ``` id/:stubId/warmup /:deploymentName/warmup /:deploymentName/latest/warmup /:deploymentName/v:version/warmup ``` ## Default Container Spin-down Times After handling a request, Beam keeps containers running ("warm") for a certain amount of time in order to quickly handle future requests. By default, these are the container "keep warm" times for each deployment type: | Deployment Type | Container Keep Warm Duration | | - | - | | Endpoints/ASGI/Realtime | 180s | | Task Queues | 10s | | Pods | 600s | # Pre-Loading Models Source: https://docs.beam.cloud/v2/endpoint/loaders This guide shows how you can optimize performance by pre-loading models when your container first starts. Beam includes an optional `on_start` lifecycle hook which you can add to your functions. The `on_start` function will be run exactly once when your container first starts. ```python app.py theme={null} from beam import endpoint def download_models(): # Do something that only needs to happen once return {} # The on_start function runs once when the container starts @endpoint(on_start=download_models) def handler(): return {} ``` Anything returned from `on_start` can be retrieved in the `context` variable that is automatically passed to your handler: ```python theme={null} from beam import endpoint def download_models(): # Do something that only needs to happen once x = 10 return {"x": x} # The on_start function runs once when the container starts @endpoint(on_start=download_models) def handler(context): # Retrieve cached values from on_start on_start_value = context.on_start_value return {} ``` # Example: Downloading Model Weights ```python theme={null} from beam import Image, endpoint, Volume CACHE_PATH = "./weights" def download_models(): from transformers import AutoTokenizer, OPTForCausalLM model = OPTForCausalLM.from_pretrained("facebook/opt-125m", cache_dir=CACHE_PATH) tokenizer = AutoTokenizer.from_pretrained("facebook/opt-125m", cache_dir=CACHE_PATH) return model, tokenizer @endpoint( on_start=download_models, volumes=[Volume(name="weights", mount_path=CACHE_PATH)], cpu=1, memory="16Gi", gpu="T4", image=Image( python_version="python3.8", python_packages=[ "transformers", "torch", ], ), ) def predict(context, prompt): # Retrieve cached model from on_start function model, tokenizer = context.on_start_value # Generate inputs = tokenizer(prompt, return_tensors="pt") generate_ids = model.generate(inputs.input_ids, max_length=30) result = tokenizer.batch_decode( generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False )[0] print(result) return {"prediction": result} ``` ## Using Loaders with Multiple Workers > [!TIP] > > If you are scaling out vertically with > [workers](/v2/scaling/concurrent-inputs#increasing-throughput-in-a-single-container), > the loader function will run once for each worker that starts up. # Creating a Web Endpoint Source: https://docs.beam.cloud/v2/endpoint/overview Deploying and invoking web endpoints on Beam Beam allows you to deploy web endpoints that can be invoked via HTTP requests. These endpoints can be used to run arbitrary code. For instance, you could perform inference using one of our GPUs, or just run a simple function that multiplies two numbers. ```python theme={null} from beam import endpoint @endpoint( cpu=1.0, memory=128, ) def multiply(**inputs): result = inputs["x"] * 2 return {"result": result} ``` > [!TIP] > > **Endpoints vs. Task Queues** > > Endpoints are RESTful APIs, designed for synchronous tasks that can complete in 180 seconds or less. For longer running tasks, you'll want to use an asynchronous [`task_queue`](/v2/task-queue/running-tasks) instead. #### Launch a Preview Environment (Optional) [`beam serve`](/v2/reference/cli#serve) monitors changes in your local file system, live-reloads the remote environment as you work, and forwards remote container logs to your local shell. Serve is great for prototyping. You can develop in a containerized cloud environment in real-time, with adjustable CPU, memory, GPU resources. It's also great for testing an app before deploying it. Served functions are orchestrated identically to deployments, which means you can test your Beam workflow end-to-end before deploying. To start an ephemeral `serve` session, you'll use the `serve` command: ```sh theme={null} beam serve [FILE.PY]:[ENTRY-POINT] ``` For example, to start a session for the `multiply` function in `app.py`, run: ```sh theme={null} beam serve app.py:multiply ``` To end the session, you can use `Ctrl + C` in the terminal where you started the session. > [!WARNING] > > Serve sessions end automatically after 10 minutes of inactivity. The entire > duration of the session is counted towards billable usage, even if the session > is not receiving requests. > [!TIP] > > By default, Beam will sync all the files in your working directory to the > remote container. This allows you to use the files you have locally while > developing. If you want to prevent some files from getting uploaded, you can > create a [`.beamignore`](/v2/reference/cli#ignore-local-files). ### Deploying the Endpoint When you're finished with prototyping and want to make a persistent deployment of the endpoint, enter your shell and run this command from the working directory: ```bash theme={null} beam deploy [FILE.PY]:[ENTRY-POINT] ``` After running this command, you'll see some logs in the console that show the progress of your deployment. > [accordion] Show Logs > > ```bash theme={null} > $ beam deploy app.py:multiply > > => Building image > => Using cached image > => Syncing files > Reading .beamignore file > => Files synced > => Deploying endpoint > => Deployed > => Invocation details > > curl -X POST 'https://multiply-712408b-v1.app.beam.cloud' \ > -H 'Accept: _/_' \ > -H 'Accept-Encoding: gzip, deflate' \ > -H 'Connection: keep-alive' \ > -H 'Authorization: Bearer [YOUR_AUTH_TOKEN]' \ > -H 'Content-Type: application/json' \ > -d '{}' > > ``` > [!NOTE] > > The container handling the endpoint will spin down after 180 seconds of inactivity by default, or customized with the `keep_warm_seconds` parameter. The container will be billed for the time it is active and handling requests. ### Calling the Endpoint After deploying the API, you'll be able to make a web request to hit the API with cURL or libraries of your choice. > [tab] cURL > > Open another terminal window to invoke the API: > > ### Example Request > > ```sh theme={null} > curl -X POST 'https://multiply-712408b-v1.app.beam.cloud' \ > -H 'Accept: */*' \ > -H 'Accept-Encoding: gzip, deflate' \ > -H 'Connection: keep-alive' \ > -H 'Authorization: Bearer [YOUR_AUTH_TOKEN]' \ > -H 'Content-Type: application/json' \ > -d '{"x": 10}' > ``` > > ### Example Response > > ```json theme={null} > { > "result": 20 > } > ``` > [tab] Python > > In Python, you can use the `requests` library to make a POST request to the endpoint: > > ```python theme={null} > import requests > > url = "https://multiply-712408b-v1.app.beam.cloud" > headers = { > "Connection": "keep-alive", > "Content-Type": "application/json", > "Authorization": "Bearer [YOUR_AUTH_TOKEN]", > } > data = {"x": 10} > > response = requests.post(url, headers=headers, json=data) > print(response.json()) > ``` > > ### Example Response > > ```json theme={null} > { "result": 20 } > ``` To send other payloads other than JSON, you can encode the data as a base64 string and include it in the JSON payload, or upload the file to a S3 bucket and mount the bucket to the endpoint. For more detailed examples, checkout the [Sending File Payloads](/v2/endpoint/sending-file-payloads) documentation. ``` ``` # Realtime and Streaming Source: https://docs.beam.cloud/v2/endpoint/realtime ## Deploying a Realtime App This is a simple example of a realtime streaming app. When deployed, this app will be exposed as a public websocket endpoint. The `realtime` handler accepts a single parameter, called `event`, with the event payload. > [!TIP] > > The `realtime` decorator is an abstraction above `asgi`. > > This means that additional parameters in `asgi`, such as [`concurrent_requests`](/v2/endpoint/web-server#concurrent-requests) can be used too. ```python app.py theme={null} from beam import realtime @realtime( cpu=1, memory="1Gi", concurrent_requests=10, # Process 10 requests at a time authorized=False, # Don't require auth to invoke ) def stream(event): # Echo back the event payload sent to the websocket return {"response": event} ``` This app can be deployed in traditional Beam fashion: ```sh theme={null} beam deploy app.py:stream ``` ## Streaming Responses from the Client Realtime Endpoints can be connected to from any websocket client. > [tab] Beam Javascript SDK > > The code below uses the Beam Javascript SDK to send requests to the realtime app. > > Make sure to add an `.env` file to your project with your `BEAM_DEPLOYMENT_ID` and `BEAM_TOKEN`: > > ```javascript client.js theme={null} > import beam from "@beamcloud/beam-js"; > > const streamResponse = async () => { > const client = await beam.init(process.env.BEAM_TOKEN); > const deployment = await client.deployments.get({ id: process.env.BEAM_DEPLOYMENT_ID }); > > const connection = await deployment.realtime(); > > const payload = { > "event": "Echo this back", > } > > connection.onmessage = (message) => { > console.log(`Response: ${message.data}`); > }; > > connection.send(JSON.stringify(payload)); > > setTimeout(() => { > connection.close(); > }, 1000); > }; > > streamResponse(); > ``` > [tab] Javascript > > The code below uses the native WebSocket API to send requests to the realtime app. > > ```javascript client.js theme={null} > const socket = new WebSocket("wss://1c0f0cbe-e0d1-49ae-a556-5daffe23eb4c.app.beam.cloud"); > > // Connection opened > socket.addEventListener("open", (event) => { > socket.send("Hello Server!"); > }); > > // Listen for messages > socket.addEventListener("message", (event) => { > console.log(event.data); // {"response":"Hello Server!"} > }); > ``` # Sending File Payloads Source: https://docs.beam.cloud/v2/endpoint/sending-file-payloads Sending file payloads to Endpoints and Web Servers There are two easy ways to send files to your Beam endpoints and ASGI web servers. ## Sending Files to Endpoints Using Base64 The simplest way to send files to your Beam endpoint is to use Base64 encoding. In the example below, we will use this method to send an image to an endpoint. The first step is to define an endpoint that accepts an encoded string. ```python theme={null} import base64 import io from beam import endpoint from beam import Image as BeamImage from PIL import Image @endpoint(name="image_endpoint", image=BeamImage().add_python_packages(["pillow"])) def image_endpoint(image: str): image = base64.b64decode(image) image = Image.open(io.BytesIO(image)) # do something with the image return {"message": "Image processed successfully"} ``` We can then deploy our endpoint with the command `beam deploy app.py:image_endpoint`. The simple script below can be used to send an image to the endpoint. ```python Python theme={null} import base64 import requests with open("./cool-picture.png", "rb") as image_file: encoded_string = base64.b64encode(image_file.read()) b64_image = encoded_string.decode("utf-8") url = "https://image-endpoint-53b4230-v1.app.beam.cloud" headers = { "Connection": "keep-alive", "Content-Type": "application/json", "Authorization": "Bearer ", } data = {"image": b64_image} response = requests.post(url, headers=headers, json=data) ``` ```bash Curl theme={null} export B64_FILE=$(base64 -i ./cool-picture.png) curl -X POST "https://image-endpoint-53b4230-v1.app.beam.cloud" \ -H 'Connection: keep-alive' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer ' \ -d '{"image": "$B64_FILE"}' ``` ## Using S3 to Send Files With Beam, you can easily [mount S3 buckets](/v2/data/external-storage) to your endpoints and web servers. This allows you to upload files to S3 and access them in your endpoint or web server. This method is recommended if you are sending large payloads (20+ MB). Another benefit of using S3 is that you will not need to include decoding logic in your endpoint. We can modify our previous example by accepting a filename and reading the image from a mounted S3 bucket. Our frontend will need to upload the image to the S3 bucket and then pass the filename to our endpoint. ```python theme={null} import os from beam import CloudBucket, CloudBucketConfig, endpoint from beam import Image as BeamImage from PIL import Image mount_path = "./uploads" uploads = CloudBucket( name="uploads", mount_path=mount_path, config=CloudBucketConfig( access_key="BEAM_S3_KEY", secret_key="BEAM_S3_SECRET", ), ) @endpoint(name="image_endpoint", image=BeamImage().add_python_packages(["pillow"]), volumes=[uploads]) def image_endpoint(image_name: str): image_path = os.path.join(uploads.mount_path, image_name) image = Image.open(image_path) # do something with the image return {"message": "Image processed successfully"} ``` In order to correctly mount the S3 bucket, we need to make sure that our secrets are set. We can do this using the Beam CLI. ```bash theme={null} beam secret create BEAM_S3_KEY "your-access-key" beam secret create BEAM_S3_SECRET "your-secret-key" ``` Once again, we can deploy our endpoint with the command `beam deploy app.py:image_endpoint`. To test this method, we can upload an image to the S3 bucket using the [AWS CLI](https://docs.aws.amazon.com/cli/latest/reference/s3/cp.html) and then pass the filename to our endpoint. ```bash theme={null} aws s3 cp ./test.png s3://uploads/ ``` The image will be uploaded to the S3 bucket and the endpoint will be able to read it. We can verify this by invoking our endpoint with the filename. ```bash theme={null} curl -X POST "https://image-endpoint-53b4230-v1.app.beam.cloud" \ -H 'Connection: keep-alive' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer ' \ -d '{"image_name": "test.png"}' ``` # Versioning Source: https://docs.beam.cloud/v2/endpoint/versioning Each time you run `beam deploy`, Beam creates a new version of your app. Deploying a new version doesn't stop the previous one: older versions keep serving their own URLs until you stop them with [`beam deployment stop`](/v2/reference/cli#stop). Endpoints, ASGI apps, and task queues get URLs in this format: `https://[APP-NAME]-[APP-ID]-v[VERSION].app.beam.cloud` `APP-ID` is a short ID that stays the same every time you deploy an app with the same name. `beam deploy` prints the URL of the version it just created, such as `https://multiply-712408b-v1.app.beam.cloud`. ### Accessing the Latest Version The URL without a version suffix routes to the latest active version, so it's the one to use in clients that should pick up new deploys. A `-latest` suffix does the same: ``` https://multiply-712408b.app.beam.cloud https://multiply-712408b-latest.app.beam.cloud ``` ### Invoking Specific Versions You can invoke specific versions of your apps by specifying the version in the app URL. Here are some examples: * To invoke latest: `https://multiply-712408b.app.beam.cloud` * To invoke version `3`: `https://multiply-712408b-v3.app.beam.cloud` * To invoke version `17`: `https://multiply-712408b-v17.app.beam.cloud` A versioned URL only works while that version is active. A version that doesn't exist returns `404`, and a stopped version returns a `5xx` error. Use the URLs that the CLI or dashboard returns rather than building these hostnames yourself. An active version may still be starting or have no running containers. See [deployment readiness, rollout, and rollback](/v2/hosting/deployments). ### Calling an App by Name You can also call an app by name on `app.beam.cloud`: * Latest version: `https://app.beam.cloud/endpoint/multiply` or `https://app.beam.cloud/endpoint/multiply/latest` * Version `3`: `https://app.beam.cloud/endpoint/multiply/v3` Task queues and ASGI apps use the same patterns under `/taskqueue/` and `/asgi/`. These URLs always require an auth token, even for [public endpoints](/v2/topics/public-endpoints). A version that doesn't exist returns `400` with `Invalid deployment`, and a stopped version returns `400` with `Deployment is not active`. > [!NOTE] > > Pods use the same scheme with the port number added at the end. See [Pod > URLs](/v2/pod/web-service#pod-urls). # Hosting a Web Server Source: https://docs.beam.cloud/v2/endpoint/web-server Deploying web servers on Beam > [!TIP] > > There are three ways to serve HTTP on Beam: an ASGI app such as FastAPI ([Hosting a Web Server](/v2/endpoint/web-server)), any Dockerfile or registry image ([Deploy Containers](/v2/hosting/containers)), or a container defined in Python with `Pod` ([Host a Web Service](/v2/pod/web-service)). With Beam, you can deploy web servers that use the [ASGI](https://asgi.readthedocs.io/en/latest/introduction.html) protocol. This means that you can deploy applications built with popular frameworks like FastAPI and Django. ## Multiple Endpoints Per App In the example below, we are deploying a FastAPI web server that uses the Huggingface Transformers library to perform sentiment analysis and text generation. We also included a warmup endpoint so that we can preemptively get our container ready for incoming requests. > [!NOTE] > > This example uses Pydantic to serialize request inputs. [You can read more > about it here](https://fastapi.tiangolo.com/tutorial/body/). ```python app.py theme={null} from beam import Image, asgi from pydantic import BaseModel # Request payload for API, declared with Pydantic class GenerateInput(BaseModel): text: str max_length: int class SentimentInput(BaseModel): text: str def init_models(): from transformers import pipeline model = "gpt2" # Initialize two simple models sentiment_analyzer = pipeline("sentiment-analysis") text_generator = pipeline("text-generation", model="gpt2") return sentiment_analyzer, text_generator, model @asgi( name="sentiment-and-generation", image=Image(python_packages=["transformers", "torch", "fastapi", "pydantic"]), on_start=init_models, memory=2048, ) def handler(context): import asyncio from fastapi import FastAPI, Query app = FastAPI() sentiment_analyzer, text_generator, generate_model = context.on_start_value @app.post("/sentiment") async def analyze_sentiment(input: SentimentInput): # Unpack request input and send to ML model result = sentiment_analyzer(input.text) return result @app.post("/generate") async def generate_text(input: GenerateInput): result = text_generator(input.text, max_length=input.max_length) return result @app.post("/warmup") async def warmup(): return {"status": "warm"} return app ``` > [!NOTE] > > As shown above, the handler function for the web server must return the ASGI > app object. ## Launch a Preview Environment (Optional) Just like an endpoint, you can prototype your web server using [`beam serve`](/v2/reference/cli#serve). This command will monitor changes in your local file system, live-reload the remote environment as you work, and forward remote container logs to your local shell. ```sh theme={null} beam serve app.py:web_server ``` > [!WARNING] > > Serve sessions end automatically after 10 minutes of inactivity. The entire > duration of the session is counted towards billable usage, even if the session > is not receiving requests. ## Deploying the Web Server When you are ready to deploy your web server, run the following command: ```bash theme={null} beam deploy app.py:web_server ``` You'll see some logs in the console that show the progress of your deployment. ```bash theme={null} => Building image => Syncing files ... => Invocation details curl -X POST 'https://sentiment-and-generation-53b4230-v1.app.beam.cloud' \ -H 'Connection: keep-alive' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer [YOUR_AUTH_TOKEN]' \ -d '{}' ``` > [!NOTE] > > The container handling the app will spin down after 180 seconds of inactivity > by default, or customized with the `keep_warm_seconds` parameter. The > container will be billed for the time it is active and handling requests. ## Sending Requests If we wanted to perform sentiment analysis using our deployed example from above, we would send a POST request like this: ```bash theme={null} curl -X POST 'https://sentiment-and-generation-53b4230-v1.app.beam.cloud/generate' \ -H 'Connection: keep-alive' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer [YOUR_AUTH_TOKEN]' \ -d '{"text": "The meaning of life is "}' ``` ## Concurrent Requests When building an ASGI app, you can specify the number of concurrent requests your app can handle using the `concurrent_requests` parameter in the `@asgi` decorator. ```python theme={null} @asgi( name="sentiment-and-generation", image=Image(python_packages=["transformers", "torch", "fastapi", "pydantic"]), on_start=init_models, memory=1024, concurrent_requests=10 ) def handler(**inputs): ... # Add the handler implementation shown below. ``` This allows you to increase the number of requests your app can handle at once, which can help you achieve higher throughput. For instance, if your app is doing I/O-bound work, additional requests can be handled while your I/O operations complete in the background. We can simulate this by adding a `model` endpoint that pretends to do some expensive I/O to our example from above. ```python theme={null} @app.get("/model") async def model(model: str = Query(...)): # Pretend we're doing expensive I/O here to demonstrate the value of concurrent requests await asyncio.sleep(10) return {"model": model} ``` Now, if you send a request to `model` and then send another request to `generate`, you will see that the second request will complete before the first. ```bash Model Request theme={null} curl -X GET 'https://sentiment-and-generation-53b4230-v1.app.beam.cloud/model?model=gpt2' \ -H 'Connection: keep-alive' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer [YOUR_AUTH_TOKEN]' \ ``` ```bash Generate Request theme={null} curl -X POST 'https://sentiment-and-generation-53b4230-v1.app.beam.cloud/generate' \ -H 'Connection: keep-alive' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer [YOUR_AUTH_TOKEN]' \ -d '{"text": "Bananas are ", "max_length": 50}' ``` ## Response Types Beam supports various response types, including any FastAPI response type. [You can find a list of FastAPI response types here](https://fastapi.tiangolo.com/advanced/custom-response/). ## Uploading Local Files If your web server needs access to local files like model weights or other resources, you can use [Beam volumes](/v2/data/volume). To add files to a volume, you can use the `beam cp` command. ```bash theme={null} beam cp [local-file] beam://[volume-name] ``` Then, you can define a volume and pass it into your `@asgi` decorator like this: ```python theme={null} from beam import asgi, Volume, Image @asgi( name="sentiment-analysis", image=Image(python_packages=["fastapi"]), volumes=[Volume(name="model-weights", mount_path="./model_weights")], ) def web_server(): from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): with open("./model_weights/somefile.txt", "r") as f: return {"message": f.read()} return app ``` # Container Images Source: https://docs.beam.cloud/v2/environment/custom-images Applications on Beam are run inside *containers*. A container is like a lightweight VM that packages a set of software packages required by your application. The benefit of using containers is portability. The required runtime environment is packaged alongside the application. Containers are based on container *images* which are instructions for how a container should be built. Because you are building a custom application, it is likely that your application depends on some custom software to run. This could include custom python packages, libraries, binaries, and drivers. You can customize the container image used to run your Beam application with the [`Image`](/v2/reference/py-sdk#image) class. The options specified in the `Image` class will influence how the image is built. ## Exploring the Beam Image Class Every application that runs on Beam instantiates the [`Image`](/v2/reference/py-sdk#image) class. This class provides a variety of methods for customizing the container image used to run your application. It exposes options for: * Installing a specific version of Python * Adding custom shell commands that run during the build process * Adding custom Python packages to install in the container * Choosing a custom base image to build on top of * Using a custom Dockerfile to build your own base image * Setting up a custom conda environment using micromamba > [!TIP] > > The default Beam image uses `ubuntu:22.04` as its base and installs Python > 3.10. ```python theme={null} from beam import function, Image image = Image() # This function will use ubuntu:22.04 with Python 3.10 @function(image=image) def hello_world(): return "Hello, world!" hello_world.remote() ``` ## Adding Python Packages The most common way to customize your image is to add the Python packages required by your application. This is done by calling the `add_python_packages` method on the `Image` object with a list of package names. > [!TIP] > > Pinning the version of the package is recommended. This ensures that when you > re-deploy your application, you won't accidentally pick up a new version that > breaks your application. ```python theme={null} from beam import Image, endpoint image = Image(python_version="python3.11").add_python_packages(["numpy==2.2.0"]) @endpoint(image=image) def handler(): return {} ``` ### Importing `requirements.txt` If you already have a `requirements.txt` file, you can also use that directly using the `Image` constructor's `python_packages` parameter: ```python theme={null} from beam import Image, endpoint image = Image(python_version="python3.11", python_packages="requirements.txt") @endpoint(image=image) def handler(): return {} ``` ## Adding Shell Commands Sometimes, it is necessary to run additional shell commands while building your image. This can be achieved by calling the `add_commands` method on the `Image` object with a list of commands. For instance, you might need to install `libjpeg-dev` when using the `Pillow` library. In the example below, we'll install `libjpeg-dev` and then install `Pillow`. ```python theme={null} from beam import Image, endpoint image = ( Image(python_version="python3.11") .add_commands(["apt-get update", "apt-get install libjpeg-dev -y"]) .add_python_packages(["Pillow"]) ) @endpoint(image=image) def handler(): return {} ``` ## Customizing the Base Image Some applications and libraries require specific dependencies that are not available in the default Beam image. In these cases, you can use a custom base image. Some of the most common custom base images are the CUDA development images from NVIDIA (e.g. `nvcr.io/nvidia/cuda:12.4.1-cudnn-devel-ubuntu22.04`). These images come with additional libraries, debugging tools, and `nvcc` installed. The image below will use a custom CUDA image as the base. ```python theme={null} from beam import Image, function image = Image( base_image="nvcr.io/nvidia/cuda:12.4.1-cudnn-devel-ubuntu22.04" ) @function(image=image) def hello_world(): return "Hello, world!" hello_world.remote() ``` ### CUDA Drivers & NVIDIA Kernel Drivers When choosing a custom base image, it is important to understand the difference between the NVIDIA Kernel Driver and the CUDA Runtime & Libraries. | **Component** | **Location** | **Role** | | - | - | - | | **NVIDIA Kernel Driver** | **Host Machine** | Low-level GPU management, talks directly to hardware. | | **CUDA Runtime & Libraries** | **Container** | Provides high-level APIs and libraries for applications. | The NVIDIA Kernel Driver on the host must support the CUDA version used by the container. In general, if the CUDA version on the host is greater than or equal to the CUDA version in the container, then the NVIDIA Kernel Driver on the host will support the CUDA version used by the container. > [!TIP] > > For example, using a CUDA 12.4 image on a host with a CUDA 12.9 driver will > work. However, using a CUDA 13.0 image on a host with a CUDA 12.9 driver > *will not* work. You can consult the table below to help you choose a compatible base image. Driver versions differ by GPU type and are upgraded as the fleet is updated, so treat this as a snapshot (last verified July 30, 2026): | GPU | Driver Version | Max Supported CUDA | | - | - | - | | A10G | 575.57.08 | 12.9 | | RTX4090 | 580.126.18 | 13.0 | > [!NOTE] > > Fleet drivers get updated ahead of the docs, so `nvidia-smi` is the > authoritative source. To check the driver on the GPU you plan to use, run > `nvidia-smi` inside a container on that GPU — [here's an > example](/v2/environment/gpu#running-tasks-on-gpu). ## Using a Specific Python Version To install a specific version of Python, you can use the `python_version` parameter: ```python theme={null} from beam import function, Image # This function will use ubuntu:22.04 with Python 3.11 @function(image=Image(python_version="python3.11")) def hello_world(): return "Hello, world!" hello_world.remote() ``` This function will use the CUDA image as the base and install Python 3.10 because no `python_version` is specified and the CUDA image has no Python version installed. ```python theme={null} from beam import Image, function @function( image=Image( base_image="nvcr.io/nvidia/cuda:12.4.1-cudnn-devel-ubuntu22.04", ) ) def custom_image_no_python(): return "Hello, world!" ``` This function will use the CUDA image as the base and install Python 3.11 because a `python_version` *is* specified. ```python theme={null} from beam import Image, function @function( image=Image( base_image="nvcr.io/nvidia/cuda:12.4.1-cudnn-devel-ubuntu22.04", python_version="python3.11", ) ) def custom_image_python_requested(): return "Hello, world!" ``` If your image comes with a pre-installed version of Python3, it will be used by default *as long as* you don't specify a `python_version` in your `Image` constructor. This function will use the PyTorch image as the base and will use the Python version that already exists in the PyTorch image. ```python theme={null} from beam import Image, function @function( image=Image( base_image="docker.io/pytorch/pytorch:2.2.1-cuda12.1-cudnn8-devel" ) ) def custom_image_pytorch(): return "Hello, world!" ``` ## Building on GPU By default, Beam builds your images on CPU-only machines. However, sometimes you might need the build to occur on a machine with a GPU. For instance, some libraries might compile CUDA kernels during installation. In these cases, you can use the `build_with_gpu()` command to run your build on the GPU of your choice. ```python theme={null} from beam import Image image = ( Image() .add_commands( [ "apt-get update -y", "apt-get install ffmpeg -y", "apt-get install nvidia-cuda-toolkit -y", # Requires GPU to install ] ) .build_with_gpu(gpu="T4") # Install on a T4 ) ``` ## Building with Environment Variables Often, shell commands require certain environment variables to be set. You can set these using the `with_envs` command: ```python theme={null} from beam import Image image = ( Image() .add_python_packages(["huggingface_hub[cli]", "accelerate"]) .with_envs(["HF_HUB_ENABLE_HF_TRANSFER=1", "HF_HOME=/models"]) .add_commands(["huggingface-cli download meta-llama/Llama-3.2-3B"]) ) ``` ### Injecting Secrets Use `with_secrets` to keep credential values out of source code and Dockerfiles. Build commands receive the real values as environment variables; this is separate from [brokered runtime secrets for VMs and sandboxes](/v2/environment/secrets#brokered-secrets-for-vms-and-sandboxes). > [!TIP] > > You can create secrets like this, using the CLI: `beam secret create HF_TOKEN `. ```python theme={null} from beam import Image image = ( Image() .add_python_packages(["huggingface_hub[cli]", "accelerate"]) .with_envs(["HF_HUB_ENABLE_HF_TRANSFER=1", "HF_HOME=/models"]) .with_secrets(["HF_TOKEN"]) # Models with a user agreement often require a token .add_commands(["huggingface-cli download meta-llama/Llama-3.2-3B"]) ) ``` **Note** Adding secrets and environment variables to the build environment *does not* make them available in the runtime environment. Runtime environment variables and secrets must be specified in the function decorator directly: ```python theme={null} from beam import function @function(env={"HF_HOME": "/models"}, secrets=["HF_TOKEN"]) def download_model(): return "Hello, world!" ``` ## Using a Dockerfile You also have the option to build your own custom base image using a Dockerfile. The `from_dockerfile()` command accepts a path to a valid Dockerfile as well as an optional path to a context directory: ```python theme={null} from beam import Image, endpoint image = Image().from_dockerfile("./Dockerfile").add_python_packages(["numpy"]) @endpoint(image=image, name="test_dockerfile") def handler(): return {} ``` The context directory serves as the root for any paths used in commands like `COPY` and `ADD`, meaning all relative paths are relative to this directory. The image built from your Dockerfile will be used as the base image for a Beam application. > [!NOTE] > > Ports *will not* be exposed in the runtime environment, and the entrypoint > will be overridden. ## Conda Environments Beam supports using Anaconda environments via [micromamba](https://mamba.readthedocs.io/en/latest/user_guide/micromamba.html). To get started, you can chain the `micromamba` method to your `Image` definition and then specify packages and channels via the `add_micromamba_packages` method. ```python theme={null} from beam import Image image = ( Image(python_version="python3.11") .micromamba() .add_micromamba_packages(packages=["pandas", "numpy"], channels=["conda-forge"]) .add_python_packages(packages=["huggingface-hub[cli]"]) .add_commands(commands=["micromamba run -n beta9 huggingface-cli download gpt2 config.json"]) ) ``` You can still use `pip` to install additional packages in the `conda` environment and you can run shell commands too. > [!TIP] > > If you need to run a shell command inside the conda environment, you should > prepend the command with `micromamba run -n beta9` as shown above. # Custom Registries Source: https://docs.beam.cloud/v2/environment/custom-registries Beam supports importing images from custom public and private registries. ## Public Docker Registries You can import existing images from remote Docker registries, like [Docker Hub](https://hub.docker.com/search?q=), [Google Artifact Registry](https://cloud.google.com/artifact-registry), [ECR](https://aws.amazon.com/ecr/), [GitHub Container Registry](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry), [NVIDIA](https://catalog.ngc.nvidia.com/containers) and more. Just supply a `base_image` argument to [`Image`](/v2/reference/py-sdk#image). ```python theme={null} from beam import endpoint, Image image = ( Image( base_image="docker.io/nvidia/cuda:12.3.1-runtime-ubuntu20.04", python_version="python3.9", ) .add_commands(["apt-get update -y", "apt-get install neovim -y"]) .add_python_packages(["torch"]) ) @endpoint(image=image) def handler(): import torch return {"torch_version": torch.__version__} ``` > [!WARNING] > > Beam only supports Debian-based images. In addition, make sure your image is > built for the correct x86 architecture. ## Private Docker Registries Beam supports importing images from the following private registries: [AWS ECR](https://aws.amazon.com/ecr/), [Google Artifact Registry](https://cloud.google.com/artifact-registry), [Docker Hub](https://hub.docker.com/), [GitHub Container Registry](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry), and [NVIDIA Container Registry](https://catalog.ngc.nvidia.com/containers). Private registries require credentials, and you can pass the credentials to Beam in two ways: as a dictionary, or exported from your shell so Beam can automatically lookup the values. **Passing Credentials as a Dictionary** You can provide the values for the registry as a dictionary directly, like this: ```python theme={null} from beam import Image image = Image( base_image="111111111111.dkr.ecr.us-east-1.amazonaws.com/my-app:latest", base_image_creds={ "AWS_ACCESS_KEY_ID": "xxxx", "AWS_SECRET_ACCESS_KEY": "xxxx", "AWS_REGION": "xxxx" }, ) ``` **Passing Credentials from your Environment** Alternatively, you can export your credentials in your shell and pass the environment variable names to `base_image_creds` as a list: ```python theme={null} from beam import Image image = Image( base_image="111111111111.dkr.ecr.us-east-1.amazonaws.com/my-app:latest", base_image_creds=[ "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "AWS_REGION" ], ) ``` ### AWS ECR To use a private image from Amazon ECR, export your AWS environment variables. Then configure the Image object with those environment variables. > [!TIP] > > You can authenticate with either your static AWS credentials or an AWS STS > token. If you use the AWS STS token, your `AWS_SESSION_TOKEN` key must also be > set. ```python theme={null} from beam import Image image = Image( python_version="python3.12", base_image="111111111111.dkr.ecr.us-east-1.amazonaws.com/my-image:latest", base_image_creds=["AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_REGION"] ) @endpoint(image=image) def handler(): pass ``` ### GCP Artifact Registry To use a private image from Google Artifact Registry, export your access token. ```sh theme={null} export GCP_ACCESS_TOKEN=$(gcloud auth print-access-token --project=my-project) ``` Then configure the Image object to use the environment variable. ```python theme={null} from beam import Image image = Image( python_version="python3.12", base_image="us-east4-docker.pkg.dev/my-project/my-repo/my-image:0.1.0", base_image_creds=["GCP_ACCESS_TOKEN"] ) @endpoint(image=image) def handler(): pass ``` ### NVIDIA GPU Cloud (NGC) To use a private image from NVIDIA GPU Cloud, export your API key. ```sh theme={null} export NGC_API_KEY=abc123 ``` Then configure the Image object to use the environment variable. ```python theme={null} from beam import Image image = Image( python_version="python3.12", base_image="nvcr.io/nvidia/tensorrt:24.10-py3", base_image_creds=["NGC_API_KEY"] ) @endpoint(image=image) def handler(): pass ``` ### Docker Hub To use a private image from Docker Hub, export your Docker Hub credentials. ```sh theme={null} export DOCKERHUB_USERNAME=user123 export DOCKERHUB_PASSWORD=pass123 ``` Then configure the Image object with those environment variables. ```python theme={null} from beam import Image image = Image( python_version="python3.12", base_image="docker.io/my-org/my-image:0.1.0", base_image_creds=["DOCKERHUB_USERNAME", "DOCKERHUB_PASSWORD"] ) @endpoint(image=image) def handler(): pass ``` ### GitHub Container Registry To use a private image from GitHub Container Registry, export your GitHub credentials. You will need a [personal access token](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry#authenticating-to-the-container-registry). ```sh theme={null} export GITHUB_USERNAME=user123 export GITHUB_TOKEN=token123 ``` Then configure the Image object with those environment variables. ```python theme={null} from beam import Image image = Image( python_version="python3.12", base_image="ghcr.io/my-username/my-image:0.1.0", base_image_creds=["GITHUB_USERNAME", "GITHUB_TOKEN"] ) @endpoint(image=image) def handler(): pass ``` # GPU Acceleration Source: https://docs.beam.cloud/v2/environment/gpu ## Running Tasks on GPU Pass `gpu` to a Python workload or `--gpu` to a container deployment. Install your framework and its compatible CUDA dependencies in the runtime image. ```python theme={null} from beam import function @function(gpu="A10G", memory="2Gi") def inspect_gpu(): import subprocess return subprocess.check_output(["nvidia-smi"], text=True) if __name__ == "__main__": print(inspect_gpu.remote()) ``` ## Availability ```bash theme={null} beam machine list beam pool offers --gpu H100 --nodes 1 --ttl 1h --max-spend 10 ``` `beam machine list` reports live serverless availability and on-demand inventory. GPU model names supported by the SDK are not a promise that every model is currently available serverless. Review offers for price, provider, region, and capacity, then use [compute pools](/v2/scaling/pools) for reserved hardware. ## GPU selection A priority list lets the scheduler consider alternative types that your workload supports: ```python theme={null} from beam import function @function(gpu=["T4", "A10G", "RTX4090"], memory="2Gi") def handler(): return {"ok": True} ``` Ensure the model fits the smallest GPU in the list and that its libraries support each architecture. `gpu_count` requests multiple GPUs on a suitable machine. It does not distribute an application automatically; configure your framework's multi-GPU execution separately. Availability and workspace limits still apply. ## Regions and pools Use a reserved offer's provider and region selectors when placement matters. Set the workload's `pool` to route it to that capacity. Use `beam machine list --help` and `beam pool --help` for the available filters and subcommands. # Working in Jupyter Notebooks Source: https://docs.beam.cloud/v2/environment/jupyter-notebook You can run Beam functions from Jupyter Notebook cells, which is useful for outsourcing heavy computation to Beam's serverless cloud. Beam works in local notebooks and cloud notebooks like Google Colab.