### Build Sandbox Template with Start Command (Bash) Source: https://ppio.com/docs/sandbox/sandbox-template-start-cmd Specifies how to build a sandbox template using the PPIO sandbox CLI, including the option to define a custom start command via the `-c` flag. Ensure the PPIO sandbox CLI is installed and authenticated before use. ```bash ppio-sandbox-cli template build -c "" ``` -------------------------------- ### Start Instance Source: https://ppio.com/docs/gpus/instance/reference-start-instance Initiates the process of starting a specified instance. Requires authentication and content type specification. ```APIDOC ## POST /instances/start ### Description Starts a specified instance. This endpoint requires authentication and a JSON content type. ### Method POST ### Endpoint /instances/start ### Parameters #### Request Body - **instanceId** (string) - Required - The ID of the instance to start. #### Headers - **Content-Type** (string) - Required - Must be `application/json`. - **Authorization** (string) - Required - Bearer token authentication, e.g., `Bearer {{API_KEY}}`. ### Request Example ```json { "instanceId": "your_instance_id_here" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. - **message** (string) - A confirmation message. #### Response Example ```json { "status": "success", "message": "Instance starting successfully." } ``` ``` -------------------------------- ### Start Sandbox and Connect to Terminal (Bash) Source: https://ppio.com/docs/sandbox/cli-spawn-sandbox This command initiates a PPIO sandbox environment and connects it to the terminal. It requires a template ID as an argument. Ensure the PPIO sandbox CLI tool is installed and authenticated before execution. ```bash ppio-sandbox-cli sandbox create ``` -------------------------------- ### Configure Sandbox Start Command (TOML) Source: https://ppio.com/docs/sandbox/sandbox-template-start-cmd Defines the start command for a sandbox template within the `ppio.toml` configuration file. This method allows for persistent configuration of the start command for template builds. ```toml template_id = "0r0efkbfwzfp9p7qpc1c" dockerfile = "ppio.Dockerfile" template_name = "my-agent-sandbox" start_cmd = "" ``` -------------------------------- ### Run DeepSearcher Example Script Source: https://ppio.com/docs/third-party/deepsearcher-use Executes the basic example script for DeepSearcher from the project's root directory. ```bash python examples/basic_example.py ``` -------------------------------- ### Get Sandbox Metrics using SDK (Python) Source: https://ppio.com/docs/sandbox/sandbox-metrics This snippet shows how to fetch sandbox vCPU and memory usage metrics using the Ppio Sandbox SDK in Python. It creates a sandbox, retrieves metrics, waits if necessary for data to populate, prints the metrics, and then terminates the sandbox. Proper environment variable setup is required. ```python from ppio_sandbox.code_interpreter import Sandbox import time sandbox = Sandbox.create() print('Sandbox created', sandbox.sandbox_id) metrics = sandbox.get_metrics() # 您也可以通过指定沙箱 ID 来获取指标信息 # metrics = Sandbox.get_metrics(sbx.sandbox_id) while len(metrics) <= 1: print('Waiting for metrics...') time.sleep(1) metrics = sandbox.get_metrics() print('Sandbox metrics', metrics) # 输出示例: # Sandbox metrics [SandboxMetrics(timestamp=datetime.datetime(2025, 6, 22, 6, 59, 28, 595373, tzinfo=tzutc()), cpu_used_pct=15.94, cpu_count=2, mem_used_mib=245, mem_total_mib=987), SandboxMetrics(timestamp=datetime.datetime(2025, 6, 22, 6, 59, 33, 591684, tzinfo=tzutc()), cpu_used_pct=1.1, cpu_count=2, mem_used_mib=246, mem_total_mib=987)] sandbox.kill() ``` -------------------------------- ### Set Up Python Environment and Install Agents SDK Source: https://ppio.com/docs/third-party/OpenAI-Agents-SDK This snippet demonstrates how to create a virtual environment and activate it, followed by installing the Agents SDK. It's a foundational step for using the SDK in Python projects. ```shell python -m venv env source env/bin/activate ``` -------------------------------- ### Custom Sandbox Dockerfile Example Source: https://ppio.com/docs/sandbox/sandbox-template An example `ppio.Dockerfile` for customizing a PPIO Agent sandbox environment. It starts from a base image and installs Python packages, such as 'cowsay', using `pip`. ```dockerfile # This base image is used in the documentation example, please keep it unchanged FROM image.ppinfra.com/sandbox/code-interpreter:latest # Install some python packages RUN pip install cowsay ``` -------------------------------- ### Copy Example Configuration File Source: https://ppio.com/docs/third-party/openmanus-use Copies the example configuration file 'config.example.toml' to 'config.toml' in the 'config' directory. This creates a new configuration file that can be customized. ```shell cp config/config.example.toml config/config.toml ``` -------------------------------- ### Request Image Authentication List (Bash) Source: https://ppio.com/docs/gpus/image/reference-list-repository-auths Example using curl to send a GET request to the PPIO API to retrieve a list of image repository authentication credentials. Requires an 'Authorization' header with a Bearer token. ```bash curl --location --request GET 'https://api.ppio.com/gpu-instance/openapi/v1/repository/auths' \ --header 'Authorization: Bearer {{API 密钥}}' ``` -------------------------------- ### Agent Runtime APIs Source: https://context7_llms APIs for managing and interacting with the Agent Runtime environment, including installation, quick start, and advanced features. ```APIDOC ## Agent Runtime Management API ### Description Provides endpoints for managing the Agent Runtime, including installation, configuration, and interaction with sandboxes. ### Method Various (GET, POST, PUT, DELETE) ### Endpoints - **GET /agent-runtime/installation**: Get installation instructions. - **GET /agent-runtime/quick-start**: Get quick start guide. - **POST /agent-runtime/sandbox**: Create a new sandbox. - **GET /agent-runtime/sandbox/{sandbox_id}**: Get details of a specific sandbox. - **DELETE /agent-runtime/sandbox/{sandbox_id}**: Delete a sandbox. - **POST /agent-runtime/sandbox/{sandbox_id}/command**: Execute a command within a sandbox. - **GET /agent-runtime/sandbox/{sandbox_id}/command/stream**: Stream command output. ### Parameters (Specific parameters vary by endpoint. Refer to detailed documentation for each endpoint.) ### Example Usage (Refer to specific endpoint documentation for detailed examples.) ``` -------------------------------- ### Fetch Template List - cURL Request Example Source: https://ppio.com/docs/gpus/template/reference-list-templates This cURL command demonstrates how to make a GET request to the PPIO LLMs API to retrieve a list of templates. It includes common query parameters for filtering and the necessary Authorization header. ```bash curl --location --request GET 'https://api.ppio.com/gpu-instance/openapi/v1/templates?pageSize=10&pageNum=1&name=test&channel=private&isMyCommunity=true' \ --header 'Authorization: Bearer {{API 密钥}}' ``` -------------------------------- ### Download File from Sandbox to Local System Source: https://ppio.com/docs/sandbox/filesystem-download Demonstrates how to download a file from a sandbox environment to the local file system. This involves creating a file in the sandbox, reading its content, and then writing that content to a local file. Ensure environment variables are correctly configured before running. ```javascript import fs from 'fs' import { Sandbox } from 'ppio-sandbox/code-interpreter' const sandbox = await Sandbox.create() // 在沙箱内创建一个文件用于测试 const filePathInSandbox = '/tmp/test-file' await sandbox.files.write(filePathInSandbox, "test-file-content") // 从沙箱读取文件内容 const content = await sandbox.files.read(filePathInSandbox) // 将文件写入本地文件系统 const localFilePath = './local-test-file' fs.writeFileSync(localFilePath, content) await sandbox.kill() ``` ```python from ppio_sandbox.code_interpreter import Sandbox sandbox = Sandbox.create() # 在沙箱内创建一个文件用于测试 file_path_in_sandbox = '/tmp/test-file' sandbox.files.write(file_path_in_sandbox, "test-file-content") # 从沙箱读取文件内容 content = sandbox.files.read(file_path_in_sandbox) # 将文件内容写入本地文件系统 local_file_path = './local-test-file' with open(local_file_path, 'w') as file: file.write(content) sandbox.kill() ``` -------------------------------- ### Get Image Preheat Quota - cURL Example Source: https://ppio.com/docs/gpus/image/reference-get-image-quota This snippet demonstrates how to fetch image prewarming quota information using cURL. It requires Content-Type and Authorization headers. The response includes total prewarm tasks, the limit, and per-image size limits. ```bash curl --location --request GET 'https://api.ppio.com/gpu-instance/openapi/v1/image/prewarm/quota' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer {{API_KEY}}' ``` -------------------------------- ### POST /create/cpu/instance Source: https://ppio.com/docs/gpus/instance/reference-create-cpu-instance Creates a new CPU instance with the specified configurations. This endpoint requires authentication and accepts a JSON payload detailing the instance's name, product ID, image, ports, environment variables, and more. ```APIDOC ## POST /create/cpu/instance ### Description Creates a new CPU instance with the specified configurations. This endpoint requires authentication and accepts a JSON payload detailing the instance's name, product ID, image, ports, environment variables, and more. ### Method POST ### Endpoint /create/cpu/instance ### Parameters #### Request Body - **name** (string) - Optional - CPU instance name. String, length limit: 0-255 characters. - **productId** (string) - Required - Product ID for deploying the instance. You can query by calling the [Get CPU Product List API](/gpus/reference-list-cpu-products). String, length limit: 1-255 characters. - **imageUrl** (string) - Required - Container image address. String, length limit: 1-500 characters. - **imageAuth** (string) - Optional - Image repository authentication. Format is username:password. Configure when using private images; not required for public images or PAI Cloud platform images. String, length limit: 0-10239 characters. - **imageAuthId** (string) - Optional - Image repository authentication ID. - **ports** (string) - Optional - Ports exposed by the instance. String, example: 80/http, 3306/tcp. Supported port numbers: 1-65535, where 2222, 2223, 2224 are internal ports and cannot be used. Supported port types: tcp, http. `ports` + `tools` can use up to 15 ports. - **envs** (object[]) - Optional - Instance environment variables. Array, up to 100 environment variable groups. - **key** (string) - Optional - Environment variable name. String, length limit: 0-511 characters. - **value** (string) - Optional - Environment variable value. String, length limit: 0-4095 characters. - **tools** (object[]) - Optional - Whether to enable official image support tools. Array, currently some official images only include Jupyter. `ports` + `tools` can use up to 15 ports. - **name** (string) - Optional - Tool name. Possible value: Jupyter. - **port** (string) - Optional - Port used by the tool. Supported port numbers: 1-65535, where 2222, 2223, 2224 are internal ports and cannot be used. - **type** (string) - Optional - Port type used by the tool. Possible values: tcp, http. - **command** (string) - Optional - Container startup command. This configuration overrides the Docker image's CMD. String, length limit: 0-2047 characters. - **entrypoint** (string) - Optional - Container startup entrypoint. This configuration overrides the Docker image's ENTRYPOINT. String, length limit: 0-2047 characters. - **clusterId** (string) - Optional - Specify the cluster ID to create the instance. If left blank, an instance will be created randomly in a cluster. String, length limit: 0-255 characters. - **localStorageMountPoint** (string) - Optional - Mount path for local storage. Default value: "/workspace", string, length limit: 1-4095 characters. - **networkStorages** (object[]) - Optional - Cloud storage mount configuration. Array, up to 30 cloud storages can be mounted. - **Id** (string) - Optional - Cloud storage ID. - **mountPoint** (string) - Optional - Mount path for cloud storage. Default value: "/network", string, length limit: 1-4095 characters. - **networkId** (string) - Optional - VPC network ID. Leave blank if not using VPC network. - **kind** (string) - Required - Instance type. Possible value: cpu. Fixed value is cpu. ### Request Example ```json { "name": "my-cpu-instance", "productId": "cpu-prod-123", "imageUrl": "my-docker-repo/my-cpu-image:latest", "ports": "8080/http", "envs": [ { "key": "MY_VAR", "value": "my_value" } ], "kind": "cpu" } ``` ### Response #### Success Response (200) - **id** (string) - Description: The ID of the created instance. #### Response Example ```json { "id": "instance-abc123xyz" } ``` ``` -------------------------------- ### Create Template Request Example (Bash) Source: https://ppio.com/docs/gpus/template/reference-create-template This bash script demonstrates how to make a POST request to the template creation endpoint. It includes necessary headers like Content-Type and Authorization, and a JSON payload with template configuration details. ```bash curl --location --request POST 'https://api.ppio.com/gpu-instance/openapi/v1/template/create' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer {{API 密钥}}' \ --data-raw '{ "template": { "name": "test", "type": "instance", "channel": "private", "readme": "test create template", "image": "nginx", "imageAuth": "", "startCommand": "echo test", "entrypoint": "", "rootfsSize": 60, "ports": [ {"type": "http", "ports": [80, 443]}, {"type": "tcp", "ports": [90, 95]} ], "envs": [ {"key": "test1", "value": "template1"}, {"key": "test2", "value": "test2"} ], "minCudaVersion": "11.8" } }' ``` -------------------------------- ### Python Example: Image Text Recognition with DeepSeek-OCR Source: https://ppio.com/docs/model/llm-deepseek-ocr This Python code snippet demonstrates how to use the OpenAI client to perform image text recognition with the DeepSeek-OCR model. It requires the 'openai' library and an API key. The example sends an image URL and a text prompt to the API and prints the extracted content. ```python from openai import OpenAI client = OpenAI( base_url="https://api.ppio.com/openai", api_key="", ) response = client.chat.completions.create( model="deepseek/deepseek-ocr", messages=[ { "role": "user", "content": [ { "type": "image_url", "image_url": { "url": "https://example.com/image.png" } }, { "type": "text", "text": "<|grounding|>OCR this image." } ] } ], stream=False, max_tokens=4096 ) content = response.choices[0].message.content print(content) ``` -------------------------------- ### Initialize PPIO Client and Define Weather Tool Source: https://ppio.com/docs/model/llm-function-calling Initializes the OpenAI client for PPIO, defines a 'get_weather' tool with its parameters, and sets up the initial user message for a chat completion request. This is the setup phase before making the first API call. ```python from openai import OpenAI import json client = OpenAI( base_url="https://api.ppio.com/openai", api_key="", ) model = "deepseek/deepseek-v3" # 示例函数,用于模拟获取天气数据。 def get_weather(location): """获取指定地点的当前天气""" print("调用 get_weather 函数,位置: ", location) # 在实际应用中,您需要在这里调用外部天气 API。 # 这是一个简化示例,返回硬编码数据。 return json.dumps({"位置": location, "温度": "20 摄氏度"}) tools = [ { "type": "function", "function": { "name": "get_weather", "description": "获取一个地点的天气,用户需要首先提供地点", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "城市信息, 例如:上海", } }, "required": ["location"] }, } }, ] messages = [ { "role": "user", "content": "上海的天气怎么样?" } ] ``` -------------------------------- ### Install and Configure OpenSSH Server on Ubuntu Source: https://ppio.com/docs/gpu/faq This bash script installs the OpenSSH server on an Ubuntu system, enables remote root login, configures SFTP, restarts the SSH service, and sets it to start on boot. It also includes commands for changing the root password and adding/modifying other users for SSH access. This is necessary for enabling standard SSH, SFTP, and SCP functionality within containers. ```bash # Install SSH service apt update && apt install openssh-server -y # Enable remote access sed -i 's/#PermitRootLogin.*/PermitRootLogin yes/'/etc/ssh/sshd_config # Enable SFTP service sed -i 's|Subsystem\s\+sftp\s\+/usr/lib/openssh/sftp-server|Subsystem sftp internal-sftp|' /etc/ssh/sshd_config # Start (restart) SSH service service ssh restart # Set SSH service to start on boot echo "service ssh start" >> /root/.bashrc # Modify root password passwd # Use other users to log in # Add user # useradd test # Modify user password # echo "test:654321" | chpasswd ``` -------------------------------- ### Image Authentication List Response (JSON) Source: https://ppio.com/docs/gpus/image/reference-list-repository-auths Example JSON response structure for the image authentication list. It contains a 'data' array, where each object represents an image repository authentication with its ID, name, username, and password. ```json { "data": [ { "id": "20", "name": "test", "username": "test", "password": "xxxxxxxx" } ] } ``` -------------------------------- ### Install and Use PPIO Sandbox Node.js CLI (Beta) Source: https://ppio.com/docs/sandbox/agent-runtime-installation Provides instructions for installing and using the PPIO Sandbox Node.js CLI beta version. It covers both temporary execution with npx and global installation for frequent use, including authentication and agent configuration. ```bash # Install latest beta version CLI npm install ppio-sandbox-cli@beta # First, complete authentication npx ppio-sandbox-cli auth login # Run the agent configure command to configure the Agent npx ppio-sandbox-cli agent configure ``` ```bash # Install latest beta version npm install -g ppio-sandbox-cli@beta # After installation, you can directly use the command: ppio-sandbox-cli agent configure ``` -------------------------------- ### Get Batch Results - Python and Curl Source: https://ppio.com/docs/model/llm-batch-api Download the output file containing the results of a completed batch inference job. The output file is accessible via the `output_file_id` in the Batch object and is available for 30 days. Code examples are provided for Python and Curl. ```python from openai import OpenAI client = OpenAI( base_url="https://api.ppio.com/openai/v1", api_key="", ) content = client.files.content("example-250811-1") print(content.read()) ``` ```bash export API_KEY="" curl --request GET \ --url https://api.ppio.com/openai/v1/files/{file_id}/content \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer ${API_KEY}' ``` -------------------------------- ### Prepare Batch Input File (JSONL Example) Source: https://ppio.com/docs/model/llm-batch-api Provides an example of a .jsonl file format for batch inference requests. Each line is a JSON object containing a unique 'custom_id' and a 'body' with inference parameters. It highlights the need for a consistent model per file and compatible endpoints. ```json {"custom_id": "request-1", "body": {"model": "deepseek/deepseek-v3-0324", "messages": [{"role": "user", "content": "Hello, world!"}], "max_tokens": 400}} {"custom_id": "request-2", "body": {"model": "deepseek/deepseek-v3-0324", "messages": [{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": "Hello world!"}],"max_tokens": 1000}} ``` -------------------------------- ### Fetch Template List - JSON Response Example Source: https://ppio.com/docs/gpus/template/reference-list-templates This JSON object represents a successful response from the PPIO LLMs API when fetching a list of templates. It includes an array of template objects, each with detailed properties, and the total count of matching templates. ```json { "template": [ { "Id": "1", "name": "Pytorch:v2", "readme": "...", "type": "instance", "channel": "official", "image": "test-image.ppinfra.com/test-public/pytorch:v2", "imageAuth": "", "startCommand": "", "entrypoint": "", "rootfsSize": 100, "ports": [ {"type": "http", "ports": [80]}, {"type": "tcp", "ports": [7860]} ], "envs": [{"key": "test", "value": "template"}], "tools": [{"name": "Jupyter", "describe": "Start Jupyter Notebook", "port": 8888, "type": "http"}], "createdAt": "1715760544", "recommendCards": [{"gpuSpecId": "4090.18c.60g", "cardNum": "2"}], "minCudaVersion": "11.8" } ], "total": 12 } ``` -------------------------------- ### Run PPIO LLM Agent for Text Output Source: https://ppio.com/docs/third-party/OpenAI-Agents-SDK This example demonstrates how to run a PPIO LLM agent to generate text output. It requires setting up the OpenAI client with PPIO's base URL and API key, and disabling tracing. The agent is instructed to write a haiku about recursion. ```python import os from openai import AsyncOpenAI from agents import ( Agent, Runner, set_default_openai_api, set_default_openai_client, set_tracing_disabled, ) BASE_URL = "https://api.ppio.com/openai" API_KEY = "在此处粘贴 PPIO 官网的 API Key" #此处需修改 MODEL_NAME = "在此输入模型名称" #此处需修改 # 基于PPIO不支持responses API,因此我们使用chat completions API作为示例 set_default_openai_api("chat_completions") set_default_openai_client(AsyncOpenAI(base_url=BASE_URL, api_key=API_KEY)) # 在此示例中禁用追踪# 如需使用自定义追踪处理器,请参考:https://openai.github.io/openai-agents-python/tracing/#external-tracing-processors-list set_tracing_disabled(disabled=True) agent = Agent(name="Assistant", instructions="You are a helpful assistant", model=MODEL_NAME) result = Runner.run_sync( agent, "Write a haiku about recursion in programming.") print(result.final_output) #输出示例: # Code within the code, # Functions calling themselves, # Infinite loop's dance. ``` -------------------------------- ### Generate Video with Vidu 2.0 (Python) Source: https://ppio.com/docs/models/reference-vidu-2.0-reference2video Example of generating a video using the Vidu 2.0 API with Python. This snippet demonstrates how to structure the request payload, including images, prompt, and other optional parameters. It assumes you have the necessary libraries installed and your API key is set. ```python import requests import json api_key = "YOUR_API_KEY" url = "https://api.ppio.com/v1/video/generations" headers = { "Content-Type": "application/json", "Authorization": f"Bearer {api_key}" } # Example image URL (replace with your actual image URL or base64 encoded string) image_url = "https://example.com/image1.png" payload = { "images": [image_url], "prompt": "A cinematic shot of a futuristic cityscape at sunset.", "duration": 4, "seed": 12345, "aspect_ratio": "16:9", "resolution": "720p", "movement_amplitude": "medium", "bgm": True, "watermark": False } try: response = requests.post(url, headers=headers, data=json.dumps(payload)) response.raise_for_status() # Raise an exception for bad status codes result = response.json() print(f"Task ID: {result['task_id']}") print("Use this task ID to query the task result API.") except requests.exceptions.RequestException as e: print(f"An error occurred: {e}") except json.JSONDecodeError: print("Failed to decode JSON response.") ```