### Complete code-server Setup and Access Example Source: https://github.com/blaxel-ai/docs/blob/main/Tutorials/Code-server.mdx This comprehensive example shows how to create a sandbox, set up a code-server preview, generate an access token, start the code-server process if it's not running, and print the preview URL. ```typescript import { SandboxInstance } from "@blaxel/core"; const sandboxName = "my-code-server-sandbox"; async function startCodeServer(sandbox: SandboxInstance) { await sandbox.process.exec({ name: "code-server", command: "code-server --disable-telemetry --config /root/.config/code-server/config.yaml", workingDir: "/home/user", waitForPorts: [8081], restartOnFailure: true, maxRestarts: 25, }); } async function main() { try { // Create or reuse the sandbox const sandbox = await SandboxInstance.createIfNotExists({ name: sandboxName, image: "code-server-template:latest", memory: 4096, region: "us-was-1", ports: [ { name: "preview", target: 8081, protocol: "HTTP" }, ], }); // Create preview const preview = await sandbox.previews.createIfNotExists({ metadata: { name: "code-server-preview" }, spec: { public: false, port: 8081, }, }); // Generate preview token const expiresAt = new Date(Date.now() + 1000 * 60 * 60 * 24); const token = await preview.tokens.create(expiresAt); // Start dev server if not already running const processes = await sandbox.process.list(); if (!processes.find((p) => p.name === "code-server")) { await startCodeServer(sandbox); } // Print access URL const webUrl = `${preview.spec?.url}?bl_preview_token=${token.value}`; console.log(`code-server preview URL: ${webUrl}`); } catch (error) { console.error("Error:", error); } } main(); ``` -------------------------------- ### Complete Next.js Setup and Run Example Source: https://github.com/blaxel-ai/docs/blob/main/Tutorials/Nextjs.mdx A comprehensive example demonstrating the creation of a sandbox, preview URL, token generation, dev server start, log streaming, and accessing the Next.js application. ```typescript import { SandboxInstance } from "@blaxel/core"; const sandboxName = "my-nextjs-sandbox"; const responseHeaders = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS, PATCH", "Access-Control-Allow-Headers": "Content-Type, Authorization, X-Requested-With, X-Blaxel-Workspace, X-Blaxel-Preview-Token, X-Blaxel-Authorization", "Access-Control-Allow-Credentials": "true", "Access-Control-Expose-Headers": "Content-Length, X-Request-Id", "Access-Control-Max-Age": "86400", Vary: "Origin", }; async function startDevServer(sandbox: SandboxInstance) { await sandbox.process.exec({ name: "dev-server", command: "npm run dev -- --port 3000", workingDir: "/app", waitForPorts: [3000], restartOnFailure: true, maxRestarts: 25, }); } async function main() { try { // Create or reuse the sandbox const sandbox = await SandboxInstance.createIfNotExists({ name: sandboxName, labels: { framework: "nextjs", }, image: "nextjs-template:latest", memory: 4096, }); // Create preview const preview = await sandbox.previews.createIfNotExists({ metadata: { name: "preview" }, spec: { responseHeaders, public: false, port: 3000, }, }); // Generate preview token const expiresAt = new Date(Date.now() + 1000 * 60 * 60 * 24); const token = await preview.tokens.create(expiresAt); // Start dev server if not already running const processes = await sandbox.process.list(); if (!processes.find((p) => p.name === "dev-server")) { await startDevServer(sandbox); } // Print access URL const webUrl = `${preview.spec?.url}?bl_preview_token=${token.value}`; console.log(`Next.js Preview URL: ${webUrl}`); // Stream logs const logStream = sandbox.process.streamLogs("dev-server", { onLog(log) { console.log(log) }, }); // Keep running until interrupted process.on("SIGINT", () => { logStream.close(); process.exit(0); }); } catch (error) { console.error("Error:", error); process.exit(1); } } main(); ``` -------------------------------- ### Clone Example Weather Server (Python) Source: https://github.com/blaxel-ai/docs/blob/main/Functions/Adapt-Existing-MCP-server.mdx Clones the example Python weather server from the quickstart resources repository and navigates into its directory. ```bash git clone cd quickstart-resources/weather-server-python ``` -------------------------------- ### Full development workflow example Source: https://github.com/blaxel-ai/docs/blob/main/cli-reference/commands/bl_serve.md This demonstrates a typical development workflow: starting the server with hot reload in one terminal and testing the agent locally in another. ```bash bl serve --hotreload # Terminal 1: Run server bl chat my-agent --local # Terminal 2: Test agent ``` -------------------------------- ### Install Tailscale and Start Daemon in Sandbox Source: https://github.com/blaxel-ai/docs/blob/main/Tutorials/Tailscale.mdx Connect to the sandbox terminal, install the 'tailscale' and 'iptables' packages using apk, and start the 'tailscaled' daemon in the background. ```sh # Install dependencies apk add tailscale iptables # Start the daemon tailscaled & ``` -------------------------------- ### Clone Example Weather Server (TypeScript) Source: https://github.com/blaxel-ai/docs/blob/main/Functions/Adapt-Existing-MCP-server.mdx Clones the example TypeScript weather server from the quickstart resources repository and navigates into its directory. ```bash git clone cd quickstart-resources/weather-server-typescript ``` -------------------------------- ### Complete Astro Integration Example Source: https://github.com/blaxel-ai/docs/blob/main/Tutorials/Astro.mdx This comprehensive example demonstrates the full workflow of setting up and running an Astro application within a Blaxel sandbox. It includes creating a sandbox, setting up a preview, generating a preview token, starting the dev server, streaming logs, and printing the access URL. It also includes signal handling for graceful shutdown. ```typescript import { SandboxInstance } from "@blaxel/core"; const sandboxName = "my-astro-sandbox"; const responseHeaders = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS, PATCH", "Access-Control-Allow-Headers": "Content-Type, Authorization, X-Requested-With, X-Blaxel-Workspace, X-Blaxel-Preview-Token, X-Blaxel-Authorization", "Access-Control-Allow-Credentials": "true", "Access-Control-Expose-Headers": "Content-Length, X-Request-Id", "Access-Control-Max-Age": "86400", Vary: "Origin", }; async function startDevServer(sandbox: SandboxInstance) { await sandbox.process.exec({ name: "dev-server", command: "bun run dev", workingDir: "/app", waitForPorts: [4321], restartOnFailure: true, maxRestarts: 25, }); } async function main() { try { // Create or reuse the sandbox const sandbox = await SandboxInstance.createIfNotExists({ name: sandboxName, labels: { framework: "astro", }, image: "astro-template:latest", memory: 4096, }); // Create preview const preview = await sandbox.previews.createIfNotExists({ metadata: { name: "preview" }, spec: { responseHeaders, public: false, port: 4321, }, }); // Generate preview token const expiresAt = new Date(Date.now() + 1000 * 60 * 60 * 24); const token = await preview.tokens.create(expiresAt); // Start dev server if not already running const processes = await sandbox.process.list(); if (!processes.find((p) => p.name === "dev-server")) { await startDevServer(sandbox); } // Print access URL const webUrl = `${preview.spec?.url}?bl_preview_token=${token.value}`; console.log(`Astro Preview URL: ${webUrl}`); // Stream logs const logStream = sandbox.process.streamLogs("dev-server", { onLog(log) { console.log(log) }, }); // Keep running until interrupted process.on("SIGINT", () => { logStream.close(); process.exit(0); }); } catch (error) { console.error("Error:", error); process.exit(1); } } main(); ``` -------------------------------- ### Complete example Source: https://github.com/blaxel-ai/docs/blob/main/Jobs/Manage-job-execution-ts.mdx A complete example demonstrating job creation, monitoring, and waiting for completion. ```APIDOC ## Complete example ### Description Here is a complete example demonstrating job creation, monitoring, and waiting for completion. ### Method ```typescript import { blJob } from "@blaxel/core"; const job = blJob("data-processing"); // create execution const executionId = await job.createExecution({ tasks: [{"name": "John"}, {"name": "Jane"}] }); // monitor let status = await job.getExecutionStatus(executionId); console.log(`Status: ${status}`); // wait try { const result = await job.waitForExecution(executionId, { maxWait: 180000, interval: 5000, }); console.log(`Completed: ${result.status}`); } catch (error) { console.log(`Timeout: ${error.message}`); } ``` ``` -------------------------------- ### Install Specific Version of Blaxel Go SDK Source: https://github.com/blaxel-ai/docs/blob/main/sdk-reference/sdk-go.mdx Use 'go get' to install a specific version of the Blaxel Go SDK. This is useful for managing dependencies and ensuring compatibility. ```shell go get -u 'github.com/blaxel-ai/sdk-go@v0.15.0' ``` -------------------------------- ### Complete example Source: https://github.com/blaxel-ai/docs/blob/main/Jobs/Manage-job-execution-py.mdx A complete example demonstrating synchronous job execution creation and status monitoring. ```APIDOC ## Complete example ### Description Here is a complete example using synchronous operations. ### Method `job.create_execution(request)` and `job.get_execution_status(execution_id)`. ### Request Example ```python from blaxel.core.jobs import bl_job from blaxel.core.client.models.create_job_execution_request import CreateJobExecutionRequest job = bl_job("my-job") # create execution request = CreateJobExecutionRequest(tasks=[{"name": "John"}, {"name": "Jane"}]) execution_id = job.create_execution(request) # monitor status = job.get_execution_status(execution_id) print(f"Status: {status}") ``` ### Response #### Success Response (200) - **status** (string) - The status of the job execution. #### Response Example ```json { "status": "pending" } ``` ``` -------------------------------- ### Install Framework Compatibility SDKs (npm) Source: https://github.com/blaxel-ai/docs/blob/main/sdk-reference/sdk-ts.mdx Install SDKs for agent framework compatibility using npm. Note: This example includes telemetry which might be a typo from the source. ```shell npm install @blaxel/telemetry npm install @blaxel/vercel npm install @blaxel/mastra npm install @blaxel/llamaindex ``` -------------------------------- ### Install Core SDK (bun) Source: https://github.com/blaxel-ai/docs/blob/main/sdk-reference/sdk-ts.mdx Use this command to install the core Blaxel SDK using bun. ```shell bun add @blaxel/core ``` -------------------------------- ### Develop Agent with Remote and Local Tools (LangChain/LangGraph) Source: https://github.com/blaxel-ai/docs/blob/main/Agents/Develop-an-agent-ts.mdx This example illustrates setting up an agent with LangChain/LangGraph, combining a remote 'blaxel-search' tool and a local 'weather' tool. It uses Blaxel SDK for dynamic model loading. Ensure '@blaxel/langgraph' is installed. ```typescript import { blModel, blTools } from '@blaxel/langgraph'; import { HumanMessage } from "@langchain/core/messages"; import { tool } from "@langchain/core/tools"; import { createReactAgent } from "@langchain/langgraph/prebuilt"; import { z } from "zod"; interface Stream { write: (data: string) => void; end: () => void; } export default async function agent(input: string, stream: Stream): Promise { const streamResponse = await createReactAgent({ // Load model API dynamically from Blaxel: llm: await blModel("gpt-4o-mini"), prompt: "If the user asks for the weather, use the weather tool.", // Load tools dynamically from Blaxel: tools: [ ``` -------------------------------- ### Install Blaxel SDK for Python Source: https://github.com/blaxel-ai/docs/blob/main/Tutorials/Claude-Code.mdx Set up a Python virtual environment and install the Blaxel SDK using pip. ```shell python3 -m venv .venv source .venv/bin/activate pip install blaxel ``` -------------------------------- ### Install Core SDK (npm) Source: https://github.com/blaxel-ai/docs/blob/main/sdk-reference/sdk-ts.mdx Use this command to install the core Blaxel SDK using npm. ```shell npm install @blaxel/core ``` -------------------------------- ### Install Framework Compatibility SDKs (bun) Source: https://github.com/blaxel-ai/docs/blob/main/sdk-reference/sdk-ts.mdx Install SDKs for agent framework compatibility using bun. ```shell bun add @blaxel/telemetry bun add @blaxel/vercel bun add @blaxel/mastra bun add @blaxel/llamaindex ``` -------------------------------- ### Install Telemetry SDK (bun) Source: https://github.com/blaxel-ai/docs/blob/main/sdk-reference/sdk-ts.mdx Install the Blaxel Telemetry SDK using bun for automatic trace and metric exports. ```shell bun add @blaxel/telemetry ``` -------------------------------- ### Python Dockerfile for Blaxel Jobs Source: https://github.com/blaxel-ai/docs/blob/main/Jobs/Deploy-dockerfile-jobs.mdx This Dockerfile starts from a Python base image, sets up the working directory, installs system dependencies, copies and installs Python dependencies using uv, copies the application code, sets the PATH environment variable for the virtual environment, and defines the entrypoint to run the Python application. ```Dockerfile # Start from a base Python image FROM python:3.12-slim # Set working directory WORKDIR /blaxel # Install system dependencies (if needed) RUN apt-get update && apt-get install -y \ build-essential \ # Add any other system dependencies here \ && rm -rf /var/lib/apt/lists/* # Copy requirements first for better caching COPY pyproject.toml uv.lock /blaxel/ RUN pip install uv && uv sync --refresh # Copy application code COPY . . # Set env variable to use the virtual environment ENV PATH="/blaxel/python/.venv/bin:$PATH" # Command to run when container starts, it need to provide a server running on port 80 for agent and MCP server ENTRYPOINT ["/blaxel/python/.venv/bin/python3", "-m", "src"] ``` -------------------------------- ### Install Blaxel SDK for TypeScript (bun) Source: https://github.com/blaxel-ai/docs/blob/main/Tutorials/Claude-Code.mdx Install the Blaxel core SDK using bun. Initialize a new project if necessary. ```shell bun init -m --yes # if new project bun install @blaxel/core ``` -------------------------------- ### Complete example: Synchronous job execution Source: https://github.com/blaxel-ai/docs/blob/main/Jobs/Manage-job-execution-py.mdx A complete example demonstrating synchronous job creation, status monitoring, and basic execution flow. ```python from blaxel.core.jobs import bl_job from blaxel.core.client.models.create_job_execution_request import CreateJobExecutionRequest job = bl_job("my-job") # create execution request = CreateJobExecutionRequest(tasks=[{"name": "John"}, {"name": "Jane"}]) execution_id = job.create_execution(request) # monitor status = job.get_execution_status(execution_id) print(f"Status: {status}") ``` -------------------------------- ### Install Core SDK (pnpm) Source: https://github.com/blaxel-ai/docs/blob/main/sdk-reference/sdk-ts.mdx Use this command to install the core Blaxel SDK using pnpm. ```shell pnpm install @blaxel/core ``` -------------------------------- ### Install Core SDK (yarn) Source: https://github.com/blaxel-ai/docs/blob/main/sdk-reference/sdk-ts.mdx Use this command to install the core Blaxel SDK using yarn. ```shell yarn add @blaxel/core ``` -------------------------------- ### Install Blaxel Python SDK Source: https://github.com/blaxel-ai/docs/blob/main/sdk-reference/sdk-python.mdx Use pip or uv to install the Blaxel Python SDK. uv add is useful for initializing a new project with the SDK. ```shell pip install blaxel ``` ```shell uv pip install blaxel ``` ```shell uv init && uv add blaxel ``` -------------------------------- ### Configure and start code-server via sandbox API Source: https://github.com/blaxel-ai/docs/blob/main/Tutorials/Code-server.mdx This script starts the sandbox API, waits for it to be ready, configures code-server to bind to all interfaces on port 8081 with no authentication and trusted origins, and then starts code-server via the sandbox API. ```bash #!/bin/bash # Start sandbox-api in the background echo "Starting sandbox-api on port 8080..." /usr/local/bin/sandbox-api & # Wait for sandbox-api to be ready while ! curl -s http://127.0.0.1:8080/health > /dev/null 2>&1; do sleep 0.1 done echo "Sandbox API ready" # Write code-server config to bind on port 8081 (CLI args don't override the config file) mkdir -p /root/.config/code-server cat > /root/.config/code-server/config.yaml << 'CONF' bind-addr: 0.0.0.0:8081 auth: none cert: false trusted-origins: - "*" CONF # Start code-server via the sandbox API echo "Starting code-server on port 8081 via sandbox API..." curl -s http://127.0.0.1:8080/process -X POST \ -H "Content-Type: application/json" \ -d '{"name":"code-server","command":"code-server --disable-telemetry --config /root/.config/code-server/config.yaml","workingDir":"/home/user","waitForCompletion":false, "env": {"PORT": "8081"}}' echo "code-server started via sandbox API" # Keep the entrypoint alive wait ``` -------------------------------- ### Install Telemetry SDK (npm) Source: https://github.com/blaxel-ai/docs/blob/main/sdk-reference/sdk-ts.mdx Install the Blaxel Telemetry SDK using npm for automatic trace and metric exports. ```shell npm install @blaxel/telemetry ``` -------------------------------- ### Install Telemetry SDK (yarn) Source: https://github.com/blaxel-ai/docs/blob/main/sdk-reference/sdk-ts.mdx Install the Blaxel Telemetry SDK using yarn for automatic trace and metric exports. ```shell yarn add @blaxel/telemetry ``` -------------------------------- ### Install Blaxel SDK for TypeScript (npm) Source: https://github.com/blaxel-ai/docs/blob/main/Tutorials/Claude-Code.mdx Install the Blaxel core SDK using npm. Initialize a new project if necessary. ```shell npm init # if new project npm install @blaxel/core ``` -------------------------------- ### Install Blaxel SDK for TypeScript (pnpm) Source: https://github.com/blaxel-ai/docs/blob/main/Tutorials/Claude-Code.mdx Install the Blaxel core SDK using pnpm. Initialize a new project if necessary. ```shell pnpm init # if new project pnpm install @blaxel/core ``` -------------------------------- ### Install Telemetry SDK (pnpm) Source: https://github.com/blaxel-ai/docs/blob/main/sdk-reference/sdk-ts.mdx Install the Blaxel Telemetry SDK using pnpm for automatic trace and metric exports. ```shell pnpm install @blaxel/telemetry ``` -------------------------------- ### Install Blaxel SDK for TypeScript (yarn) Source: https://github.com/blaxel-ai/docs/blob/main/Tutorials/Claude-Code.mdx Install the Blaxel core SDK using yarn. Initialize a new project if necessary. ```shell yarn init # if new project yarn add @blaxel/core ``` -------------------------------- ### Full Workflow Example Source: https://github.com/blaxel-ai/docs/blob/main/cli-reference/commands/bl_new.md Demonstrates a complete workflow from creating an agent project to testing and deploying it. This includes creating the project, navigating into the directory, testing with hot-reloading, deploying, and interacting with the deployed agent. ```bash bl new agent my-assistant cd my-assistant bl serve --hotreload # Test locally bl deploy # Deploy to Blaxel bl chat my-assistant # Chat with deployed agent ``` -------------------------------- ### Preview documentation locally Source: https://github.com/blaxel-ai/docs/blob/main/README.md Run this command at the root of the documentation directory to start a local development server. ```bash npx mint dev ``` -------------------------------- ### Start Local Agent with Blaxel CLI Source: https://github.com/blaxel-ai/docs/blob/main/Tutorials/Claude-Agent-SDK.mdx Use the `bl serve --hotreload` command to start your agent locally, enabling hot-reloading for development. ```shell bl serve --hotreload & ``` -------------------------------- ### Create Drive, Sandbox, Mount, and File Operations Source: https://github.com/blaxel-ai/docs/blob/main/Agent-drive/Overview.mdx This example demonstrates the full lifecycle of creating a drive, creating a sandbox from a custom image, mounting the drive to the sandbox, writing a file to the mounted path, and reading it back. It also shows how to list mounted drives. ```TypeScript import { SandboxInstance, DriveInstance } from "@blaxel/core"; // 1. Create a drive const drive = await DriveInstance.createIfNotExists({ name: "agent-storage", region: "us-was-1", }); // 2. Create a sandbox // Use the image ID of the custom sandbox image const sandbox = await SandboxInstance.createIfNotExists({ name: "my-agent-sandbox", image: "my-sandbox-image-id", memory: 2048, region: "us-was-1", }); // 3. Mount the drive to the sandbox await sandbox.drives.mount({ driveName: "agent-storage", mountPath: "/mnt/storage", drivePath: "/", }); // 4. Write a file to the mounted drive await sandbox.fs.write("/mnt/storage/hello.txt", "Hello from the drive!"); // 5. Read it back const content = await sandbox.fs.read("/mnt/storage/hello.txt"); console.log(content); // "Hello from the drive!" // 6. List mounted drives const mounts = await sandbox.drives.list(); console.log(mounts); ``` ```Python import asyncio from blaxel.core.drive import DriveInstance from blaxel.core import SandboxInstance async def main(): # 1. Create a drive drive = await DriveInstance.create_if_not_exists( { "name": "agent-storage", "region": "us-was-1", } ) # 2. Create a sandbox sandbox = await SandboxInstance.create_if_not_exists( { "name": "my-agent-sandbox", "image": "my-sandbox-image-id", "memory": 2048, "region": "us-was-1", } ) # 3. Mount the drive to the sandbox await sandbox.drives.mount( drive_name="agent-storage", mount_path="/mnt/storage", drive_path="/", ) # 4. Write a file to the mounted drive await sandbox.fs.write("/mnt/storage/hello.txt", "Hello from the drive!") # 5. Read it back content = await sandbox.fs.read("/mnt/storage/hello.txt") print(content) # "Hello from the drive!" # 6. List mounted drives mounts = await sandbox.drives.list() print(mounts) asyncio.run(main()) ``` -------------------------------- ### Install OpenAI Agents SDK with Blaxel Support (Python) Source: https://github.com/blaxel-ai/docs/blob/main/Tutorials/OpenAI-Agents-SDK.mdx Set up a Python virtual environment and install the OpenAI Agent SDK with Blaxel support using pip. ```shell python3 -m venv .venv && source .venv/bin/activate # if new project pip install openai-agents[blaxel] ``` -------------------------------- ### Run OpenAI Agent with Python Source: https://github.com/blaxel-ai/docs/blob/main/Tutorials/OpenAI-Agents-SDK.mdx Execute an OpenAI agent using Python. This example assumes you have Python installed and a main.py script. ```shell python main.py "My cat Kitty does amazing things. Create a website about her." ``` -------------------------------- ### Install dependencies and code-server in Dockerfile Source: https://github.com/blaxel-ai/docs/blob/main/Tutorials/Code-server.mdx Installs essential tools, Node.js packages, and code-server. It also sets up a Next.js application and copies the sandbox API and entrypoint script. ```dockerfile FROM node:23-slim RUN apt-get update && apt-get install -y \ curl \ wget \ procps \ jq \ sed \ grep \ nano \ vim \ git \ sudo \ python3 \ zip \ tree \ unzip \ ca-certificates \ && apt-get clean && rm -rf /var/lib/apt/lists/* WORKDIR /home/user RUN update-ca-certificates RUN npm i -g typescript ts-node @types/node dotenv webpack webpack-cli # Install code-server RUN curl -fsSL https://code-server.dev/install.sh | sh # Create /blaxel directory and Next.js app for testing RUN mkdir -p /blaxel && \ npx create-next-app@latest /blaxel/app --use-npm --typescript --eslint --tailwind --src-dir --app --import-alias "@/*" --no-git --yes --no-turbopack # Copy sandbox-api COPY --from=ghcr.io/blaxel-ai/sandbox:latest /sandbox-api /usr/local/bin/sandbox-api # Copy entrypoint script COPY entrypoint.sh /home/user/entrypoint.sh RUN chmod +x /home/user/entrypoint.sh ENTRYPOINT ["/home/user/entrypoint.sh"] ``` -------------------------------- ### Node.js Dockerfile for Blaxel Agents Source: https://github.com/blaxel-ai/docs/blob/main/Agents/Deploy-dockerfile.mdx This Dockerfile sets up a Node.js environment for your Blaxel agent. It installs dependencies using pnpm and defines the start command for the application. ```Dockerfile # Start from a Node.js base image FROM node:22-alpine # Set working directory WORKDIR /blaxel # Copy package files for better caching COPY package.json pnpm-lock.yaml /blaxel/ RUN npx pnpm install # Copy application code COPY . . # Command to run when container starts, it need to provide a server running on port 80 for agent and MCP server ENTRYPOINT ["npx", "pnpm", "start"] ``` -------------------------------- ### Serve with environment variables Source: https://github.com/blaxel-ai/docs/blob/main/cli-reference/commands/bl_serve.md Starts the local server and loads environment variables from a specified file. ```bash bl serve -e .env.local ``` -------------------------------- ### Retrieve and Filter Codegen Tools (TypeScript) Source: https://github.com/blaxel-ai/docs/blob/main/Sandboxes/Codegen-tools.mdx Use the Blaxel SDK to retrieve all tools from a sandbox's MCP and filter them to get only the codegen tools. Ensure the '@blaxel/vercel' package is installed. ```typescript import { blTools } from '@blaxel/vercel'; // Get codegen tools from sandbox MCP const allTools = await blTools([`sandboxes/${sandbox.metadata.name}`]); // Filter for specific codegen tools const codegenTools = Object.fromEntries( Object.entries(allTools).filter(([key]) => key.startsWith('codegen') ) ); ``` -------------------------------- ### Retrieve and Filter Codegen Tools (Python) Source: https://github.com/blaxel-ai/docs/blob/main/Sandboxes/Codegen-tools.mdx Use the Blaxel SDK to retrieve all tools from a sandbox's MCP and filter them to get only the codegen tools. This is the Python equivalent of the TypeScript example. ```python from blaxel.langgraph import bl_tools # Get codegen tools from sandbox MCP all_tools = await bl_tools([f"sandboxes/{sandbox.metadata.name}"]) # Filter for specific codegen tools codegen_tools = [tool for tool in all_tools if tool.name.startswith("codegen")] ``` -------------------------------- ### Initialize and Run a Blaxel Agent Source: https://github.com/blaxel-ai/docs/blob/main/Agents/Develop-an-agent-py.mdx Set up and run an agent with specified tools, model, and prompt. This snippet demonstrates loading tools and models dynamically and initiating an agent session. ```python APP_NAME = "research_assistant" session_service = InMemorySessionService() async def agent(input: str, user_id: str = "default", session_id: str = "default") -> AsyncGenerator[str, None]: description = "You are a helpful assistant that can answer questions and help with tasks." prompt = """ You are a helpful weather assistant. Your primary goal is to provide current weather reports. "" When the user asks for the weather in a specific city, You can also use a research tool to find more information about anything. Analyze the tool's response: if the status is 'error', inform the user politely about the error message. If the status is 'success', present the weather 'report' clearly and concisely to the user. Only use the tool when a city is mentioned for a weather request. """ ### Load tools dynamically from Blaxel, and adding a tool defined locally: tools = await bl_tools(["blaxel-search"]).to_google_adk() + [get_weather] ### Load model API dynamically from Blaxel: model = await bl_model("sandbox-openai").to_google_adk() agent = Agent(model=model, name=APP_NAME, description=description, instruction=prompt, tools=tools) # Create the specific session where the conversation will happen if not session_service.get_session(app_name=APP_NAME, user_id=user_id, session_id=session_id): session_service.create_session( app_name=APP_NAME, user_id=user_id, session_id=session_id ) logger.info(f"Session created: App='{APP_NAME}', User='{user_id}', Session='{session_id}'") runner = Runner( agent=agent, app_name=APP_NAME, session_service=session_service, ) logger.info(f"Runner created for agent '{runner.agent.name}'.") content = types.Content(role="user", parts=[types.Part(text=input)]) async for event in runner.run_async(user_id=user_id, session_id=session_id, new_message=content): # Key Concept: is_final_response() marks the concluding message for the turn. if event.is_final_response(): if event.content and event.content.parts: # Assuming text response in the first part yield event.content.parts[0].text elif event.actions and event.actions.escalate: # Handle potential errors/escalations yield f"Agent escalated: {event.error_message or 'No specific message.'}" ``` -------------------------------- ### Execute Build Commands with Blaxel SDK Source: https://github.com/blaxel-ai/docs/blob/main/Sandboxes/Templates.mdx Execute shell commands during the image build process using the `runCommands` method. This is useful for installing dependencies or performing other setup tasks within the image. ```typescript const image = ImageInstance.fromRegistry("node:20") .runCommands( "apt-get update && apt-get install -y python3 make g++" ); ``` ```python image = ( ImageInstance.from_registry("node:20") .run_commands( "apt-get update && apt-get install -y python3 make g++", ) ) ``` -------------------------------- ### Configure Tailscale in Blaxel Sandbox (TypeScript) Source: https://github.com/blaxel-ai/docs/blob/main/Tutorials/Tailscale.mdx Use this TypeScript snippet to create a sandbox, install Tailscale, start the daemon, authenticate, and retrieve the Tailscale IP. Ensure TS_AUTHKEY is set in your environment variables. ```typescript import { SandboxInstance } from "@blaxel/core"; const TS_AUTHKEY = process.env.TS_AUTHKEY!; const SANDBOX_NAME = "tailscale-sandbox"; // 1. Create sandbox with iptables enabled const sandbox = await SandboxInstance.create({ name: SANDBOX_NAME, extraArgs: { iptables: "enabled" }, }); // 2. Install dependencies await sandbox.process.exec({ name: "install-deps", command: "apk add --no-cache tailscale iptables", waitForCompletion: true, timeout: 60000, }); // 3. Start the tailscaled daemon in the background await sandbox.process.exec({ name: "tailscaled", command: "tailscaled", keepAlive: true, timeout: 0, // run indefinitely }); // Give the daemon a moment to initialize await new Promise((r) => setTimeout(r, 2000)); // 4. Authenticate and bring up the interface const up = await sandbox.process.exec({ name: "tailscale-up", command: `tailscale up --authkey=$TS_AUTHKEY --hostname=${SANDBOX_NAME} --ssh`, env: { TS_AUTHKEY }, waitForCompletion: true, timeout: 30000, }); console.log("tailscale up:", up.logs); // 5. Get the Tailscale IP const ip = await sandbox.process.exec({ name: "tailscale-ip", command: "tailscale ip", waitForCompletion: true, timeout: 10000, }); console.log("Tailscale IP:", ip.logs?.trim()); ``` -------------------------------- ### Google ADK Agent Setup Source: https://github.com/blaxel-ai/docs/blob/main/Agents/Develop-an-agent-py.mdx This snippet shows the initial imports for setting up an agent using Google ADK with Blaxel. It includes logger and session service configurations. ```python from logging import getLogger from typing import AsyncGenerator from blaxel.googleadk import bl_model, bl_tools from google.adk.agents import Agent from google.adk.runners import Runner from google.adk.sessions import InMemorySessionService from google.genai import types logger = getLogger(__name__) ``` -------------------------------- ### Configure TypeScript Scripts for npm/pnpm/yarn Source: https://github.com/blaxel-ai/docs/blob/main/Tutorials/Claude-Agent-SDK-MCP.mdx Define 'start', 'dev', and 'build' scripts in your package.json for TypeScript projects using npm, pnpm, or yarn. Ensure 'tsx' is installed for running TypeScript files directly. ```json { "scripts": { "start": "tsx index.ts", "dev": "tsx --watch index.ts", "build": "tsc" }, // ... } ``` -------------------------------- ### Complete example: Create, monitor, and wait for job execution Source: https://github.com/blaxel-ai/docs/blob/main/Jobs/Manage-job-execution-ts.mdx A comprehensive example demonstrating the creation of a job execution, monitoring its status, and waiting for its completion with error handling for timeouts. ```typescript import { blJob } from "@blaxel/core"; const job = blJob("data-processing"); // create execution const executionId = await job.createExecution({ tasks: [{"name": "John"}, {"name": "Jane"}] }); // monitor let status = await job.getExecutionStatus(executionId); console.log(`Status: ${status}`); // wait try { const result = await job.waitForExecution(executionId, { maxWait: 180000, interval: 5000, }); console.log(`Completed: ${result.status}`); } catch (error) { console.log(`Timeout: ${error.message}`); } ``` -------------------------------- ### Serve from a subdirectory Source: https://github.com/blaxel-ai/docs/blob/main/cli-reference/commands/bl_serve.md Starts the local server and serves the project from a specified subdirectory, useful for monorepos. ```bash bl serve -d packages/my-agent ``` -------------------------------- ### Develop Agent with Remote and Local Tools (LlamaIndex) Source: https://github.com/blaxel-ai/docs/blob/main/Agents/Develop-an-agent-ts.mdx This example shows how to create an agent with LlamaIndex that integrates a remote 'blaxel-search' tool and a local 'weather' tool. The model and tools are loaded dynamically using Blaxel SDK. Ensure '@blaxel/llamaindex' is installed. ```typescript import { blModel, blTools } from '@blaxel/llamaindex'; import { agent, AgentStream, tool, ToolCallLLM } from "llamaindex"; import { z } from "zod"; interface Stream { write: (data: string) => void; end: () => void; } export default async function myagent(input: string, stream: Stream): Promise { const streamResponse = agent({ // Load model API dynamically from Blaxel: llm: await blModel("gpt-4o-mini") as unknown as ToolCallLLM, // Load tools dynamically from Blaxel: tools: [...await blTools(['blaxel-search']), // And here's an example of a tool defined locally for LlamaIndex: tool({ name: "weather", description: "Get the weather in a specific city", parameters: z.object({ city: z.string(), }), execute: async (input) => { console.debug("TOOL CALLING: local weather", input) return `The weather in ${input.city} is sunny`; }, }) ], systemPrompt: "If the user asks for the weather, use the weather tool.", }).run(input); for await (const event of streamResponse) { if (event instanceof AgentStream) { for (const chunk of event.data.delta) { stream.write(chunk); } } } stream.end(); } ``` -------------------------------- ### Develop Agent with Remote and Local Tools (Vercel AI) Source: https://github.com/blaxel-ai/docs/blob/main/Agents/Develop-an-agent-ts.mdx This example demonstrates creating an agent using Vercel AI that combines a remote 'blaxel-search' tool with a local 'weather' tool. Ensure the '@blaxel/vercel' package is installed and the model is loaded dynamically. ```typescript import { blModel, blTools } from '@blaxel/vercel'; import { streamText, tool } from 'ai'; import { z } from 'zod'; interface Stream { write: (data: string) => void; end: () => void; } export default async function agent(input: string, stream: Stream): Promise { const response = streamText({ experimental_telemetry: { isEnabled: true }, // Load model API dynamically from Blaxel: model: await blModel("gpt-4o-mini"), tools: { // Load tools dynamically from Blaxel: ...await blTools(['blaxel-search']), // And here's an example of a tool defined locally for Vercel AI: "weather": tool({ description: "Get the weather in a specific city", parameters: z.object({ city: z.string(), }), execute: async (args: { city: string }) => { console.debug("TOOL CALLING: local weather", args); return `The weather in ${args.city} is sunny`; }, }), }, system: "You are an agent that will give the weather when a city is provided, and also do a quick search about this city.", messages: [ { role: 'user', content: input } ], maxSteps: 5, }); for await (const delta of response.textStream) { stream.write(delta); } stream.end(); } ``` -------------------------------- ### Install Python Packages with uv using Blaxel SDK Source: https://github.com/blaxel-ai/docs/blob/main/Sandboxes/Templates.mdx Install Python packages using uv with the `uvInstall` method after ensuring uv is installed. This method provides efficient package installation. ```typescript const image = ImageInstance.fromRegistry("python:3.11-slim") .runCommands("pip install uv") .uvInstall("requests", "httpx"); ``` ```python image = ( ImageInstance.from_registry("python:3.11-slim") .run_commands("pip install uv") .uv_install("requests", "httpx") ) ``` -------------------------------- ### Install Claude Agent SDK and Blaxel Core (bun) Source: https://github.com/blaxel-ai/docs/blob/main/Tutorials/Claude-Agent-SDK-Code-Mode.mdx Install the Claude Agent SDK and Blaxel core libraries using bun. Ensure you have initialized your project with `bun init -m --yes` if it's a new project. ```shell bun init -m --yes # if new project bun install @anthropic-ai/claude-agent-sdk @blaxel/core ``` -------------------------------- ### Install Python Packages with pip using Blaxel SDK Source: https://github.com/blaxel-ai/docs/blob/main/Sandboxes/Templates.mdx Install Python packages using pip with the `pipInstall` method. Supports simple installations and installations with custom index URLs or pre-release versions. ```typescript // Simple install const image = ImageInstance.fromRegistry("python:3.11-slim") .pipInstall("requests", "numpy>=1.20", "pandas"); // With options const image = ImageInstance.fromRegistry("python:3.11-slim") .pipInstall( { indexUrl: "https://my-private-index.com/simple", pre: true }, "my-package", "another-package" ); ``` ```python # Simple install image = ( ImageInstance.from_registry("python:3.11-slim") .pip_install("requests", "numpy>=1.20", "pandas") ) # With options image = ( ImageInstance.from_registry("python:3.11-slim") .pip_install( "my-package", "another-package", index_url="https://my-private-index.com/simple", pre=True, ) ) ``` -------------------------------- ### Install Blaxel CLI on Mac Source: https://github.com/blaxel-ai/docs/blob/main/Functions/Adapt-Existing-MCP-server.mdx Installs the Blaxel CLI using Homebrew on macOS. Ensure Homebrew is installed before running these commands. ```bash brew tap blaxel-ai/blaxel ``` ```bash brew install blaxel ``` -------------------------------- ### Install Node.js Packages with npm/pnpm using Blaxel SDK Source: https://github.com/blaxel-ai/docs/blob/main/Sandboxes/Templates.mdx Install Node.js packages using npm, pnpm, yarn, or bun with the `npmInstall` method. Supports installing specific packages, using different package managers, or installing from package.json. ```typescript // Install specific packages with npm (default) const image = ImageInstance.fromRegistry("node:20-alpine") .npmInstall("express", "typescript"); // Use a different package manager const image = ImageInstance.fromRegistry("node:20-alpine") .npmInstall( { packageManager: "pnpm", globalInstall: true }, "turbo" ); // Install from package.json (no packages specified) const image = ImageInstance.fromRegistry("node:20-alpine") .workdir("/app") .copy("package.json", "/app/package.json") .npmInstall(); ``` ```python # Install specific packages with npm (default) image = ( ImageInstance.from_registry("node:20-alpine") .npm_install("express", "typescript") ) ``` -------------------------------- ### Install npm packages from package.json Source: https://github.com/blaxel-ai/docs/blob/main/Sandboxes/Templates.mdx Installs npm packages defined in a `package.json` file. Ensure the working directory is set and the file is copied before installation. ```python image = ( ImageInstance.from_registry("node:20-alpine") .workdir("/app") .copy("package.json", "/app/package.json") .npm_install() ) ``` -------------------------------- ### Install Blaxel CLI on Linux (Non-Sudo) Source: https://github.com/blaxel-ai/docs/blob/main/Functions/Adapt-Existing-MCP-server.mdx Installs the Blaxel CLI on Linux without sudo privileges. The installation script will prompt for configuration details. ```bash curl -fsSL \ \ | sh ``` -------------------------------- ### Complete Example Script for Sandbox Deployment Source: https://github.com/blaxel-ai/docs/blob/main/Sandboxes/Templates.mdx This comprehensive shell script automates the entire sandbox deployment workflow, including creating a ZIP archive, creating the sandbox resource, uploading the archive, and monitoring deployment status. It includes error handling and cleanup. ```bash #!/bin/bash # Real deployment script that executes the documented API workflow set -e # Configuration SANDBOX_NAME="my-custom-sandbox-$(date +%s)" SOURCE_DIR="mytemplate" ZIP_FILE="mytemplate.zip" BASE_URL="https://api.blaxel.ai/v0" # Colors for output GREEN='\033[0;32m' RED='\033[0;31m' YELLOW='\033[1;33m' BLUE='\033[0;34m' NC='\033[0m' # No Color # Cleanup function cleanup() { if [ -f "$ZIP_FILE" ]; then rm -f "$ZIP_FILE" echo -e "\n${GREEN}✓ Cleaned up temporary files${NC}" fi } # Set trap to cleanup on exit trap cleanup EXIT # Validate credentials if [ -z "$BL_API_KEY" ]; then echo -e "${RED}Error: BL_API_KEY not set${NC}" echo "Get your API key from workspace settings and set it with:" echo " export BL_API_KEY='your-api-key'" exit 1 fi if [ -z "$BL_WORKSPACE" ]; then echo -e "${RED}Error: BL_WORKSPACE not set${NC}" echo "Set your workspace name with:" echo " export BL_WORKSPACE='your-workspace-name'" exit 1 fi # Check if source directory exists if [ ! -d "$SOURCE_DIR" ]; then echo -e "${RED}Error: $SOURCE_DIR directory not found${NC}" exit 1 fi # Create ZIP archive echo -e "${BLUE}Creating ZIP archive from $SOURCE_DIR...${NC}" cd "$SOURCE_DIR" zip -q -r "../${ZIP_FILE}" . cd .. FILE_SIZE=$(wc -c < "$ZIP_FILE" | tr -d ' ') echo -e "${GREEN}✓ ZIP archive created: $ZIP_FILE ($FILE_SIZE bytes)${NC}\n" # Step 1: Create sandbox and get upload URL echo -e "${BLUE}[1/4] Creating sandbox '$SANDBOX_NAME'...${NC}" ``` -------------------------------- ### Create Project Directory Source: https://github.com/blaxel-ai/docs/blob/main/Tutorials/Claude-Agent-SDK.mdx Create a new directory for your agent project and navigate into it. This sets up the workspace for your agent. ```bash mkdir assistant-agent && cd assistant-agent ``` -------------------------------- ### Get execution details Source: https://github.com/blaxel-ai/docs/blob/main/Jobs/Manage-job-execution-ts.mdx Get full execution details. ```APIDOC ## Get execution details ### Description Get full execution details. ### Method ```typescript const execution = await job.getExecution(executionId); console.log(execution.status, execution.metadata); ``` ``` -------------------------------- ### Install npm packages with a specific package manager Source: https://github.com/blaxel-ai/docs/blob/main/Sandboxes/Templates.mdx Installs npm packages using a specified package manager like pnpm. Set `global_install` to true for global installations. ```python image = ( ImageInstance.from_registry("node:20-alpine") .npm_install("turbo", package_manager="pnpm", global_install=True) ) ``` -------------------------------- ### Install Blaxel CLI on Linux/macOS with cURL (sudo) Source: https://github.com/blaxel-ai/docs/blob/main/Get-started.mdx Install the Blaxel CLI on Linux or macOS using cURL with sudo privileges. This command installs to a system-wide binary directory. ```shell curl -fsSL \ https://raw.githubusercontent.com/blaxel-ai/toolkit/main/install.sh \ | BINDIR=/usr/local/bin sudo -E sh ``` -------------------------------- ### List All Templates Source: https://github.com/blaxel-ai/docs/blob/main/cli-reference/commands/bl_get_templates.md Use this command to see all available project templates. ```bash bl get templates ``` -------------------------------- ### Install OpenAI Agents SDK with Blaxel Support (bun) Source: https://github.com/blaxel-ai/docs/blob/main/Tutorials/OpenAI-Agents-SDK.mdx Install the necessary bun packages for the OpenAI Agent SDK with Blaxel support. Initialize a new project if it doesn't exist. ```shell bun init -m --yes # if new project bun add @openai/agents-extensions @blaxel/core ``` -------------------------------- ### Initialize a new MCP server Source: https://github.com/blaxel-ai/docs/blob/main/Functions/Create-MCP-server.mdx Use the `bl new` CLI command to initialize a new, pre-scaffolded local repository for your MCP server. Ensure you have npm or uv installed. ```bash bl new mcp ``` -------------------------------- ### Install Framework Compatibility SDKs (yarn) Source: https://github.com/blaxel-ai/docs/blob/main/sdk-reference/sdk-ts.mdx Install SDKs for agent framework compatibility using yarn. ```shell yarn add @blaxel/telemetry yarn add @blaxel/vercel yarn add @blaxel/mastra yarn add @blaxel/llamaindex ``` -------------------------------- ### Create and Deploy a Sandbox using Blaxel CLI Source: https://github.com/blaxel-ai/docs/blob/main/Sandboxes/Overview.mdx Initialize a new sandbox project and deploy it on Blaxel using the CLI. This command creates the project directory and configuration file. ```shell bl new sandbox my-sandbox cd my-sandbox bl deploy ``` -------------------------------- ### Install Framework Compatibility SDKs (pnpm) Source: https://github.com/blaxel-ai/docs/blob/main/sdk-reference/sdk-ts.mdx Install SDKs for agent framework compatibility using pnpm. ```shell pnpm install @blaxel/langgraph pnpm install @blaxel/vercel pnpm install @blaxel/mastra pnpm install @blaxel/llamaindex ```