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

# 快速开始

本文档将引导你在 **5 分钟内** 完成第一个 Agent 的开发、部署和调用。

***

## 目录

* [概览](#概览)
* [前置准备](#前置准备)
* [步骤 1: 集成 SDK 到 Agent](#步骤-1-集成-sdk-到-agent)
* [步骤 2: 使用 CLI 生成配置文件](#步骤-2-使用-cli-生成配置文件)
* [步骤 3: 一键部署到 PPIO 云端](#步骤-3-一键部署到-ppio-云端)
* [步骤 4: 通过 CLI 或 SDK 调用 Agent](#步骤-4-通过-cli-或-sdk-调用-agent)
* [常见问题](#常见问题)

***

## 概览

完整流程包含 4 个步骤：

1. ✅ **集成 SDK** - 在 Agent 代码中添加装饰器
2. ✅ **配置 Agent** - 使用 CLI 生成配置文件
3. ✅ **部署 Agent** - 一键部署到云端
4. ✅ **调用 Agent** - 使用 SDK 或 CLI 调用 Agent

***

## 前置准备

确保已完成以下准备工作：

* ✅ 已安装 Python 3.9+ 和 Node.js 20+
* ✅ 已安装 Beta 版 Python SDK 和 Node.js CLI（参考 [安装指南](/sandbox/agent-runtime-installation)）
* ✅ 已获取 PPIO API Key（从 [控制台](https://ppio.com/settings/key-management) 获取）
* ✅ 已安装 [Docker](https://www.docker.com/products/docker-desktop/).

***

## 步骤 1: 集成 SDK 到 Agent

### 1.1 创建 Agent 代码

在项目目录创建 `app.py`：

```python theme={null}
from ppio_sandbox.agent_runtime import AgentRuntimeApp

# 创建 Agent Runtime 应用实例
app = AgentRuntimeApp()

# 使用装饰器定义 Agent 入口点
@app.entrypoint
def my_agent(request: dict) -> dict:
    """
    Agent 入口函数
    
    Args:
        request: 请求数据，通常包含 prompt 等字段
        
    Returns:
        响应数据字典
    """
    prompt = request.get("prompt", "")
    
    # Agent 业务逻辑
    # 这里可以调用 LLM、使用 Agent 框架、或任何自定义逻辑
    result = f"收到消息: {prompt}"
    
    return {"result": result}

# 本地运行入口
if __name__ == "__main__":
    app.run()
```

### 1.2 准备依赖文件

确保项目根目录有 `requirements.txt` 文件，包含必需的依赖：

```txt theme={null}
ppio-sandbox>=1.1.0b1
# 你的其他依赖...
```

### 1.3 本地测试

在部署前先本地测试：

```bash theme={null}
# 启动 Agent 服务
python app.py
```

在另一个终端测试：

```bash theme={null}
# 测试健康检查
curl http://localhost:8080/ping

# 测试 Agent 调用
curl -X POST http://localhost:8080/invocations \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Hello, Agent!"}'
```

**预期输出**：

健康检查应返回：

```json theme={null}
{"status": "Healthy"}
```

Agent 调用应返回：

```json theme={null}
{"result": "收到消息: Hello, Agent!"}
```

***

## 步骤 2: 使用 CLI 生成配置文件

使用 CLI 交互式配置 Agent：

```bash theme={null}
# 确保环境变量已配置
export PPIO_API_KEY=your-ppio-api-key

# 运行配置命令
npx ppio-sandbox-cli agent configure
```

根据 CLI 提示配置所需信息。完成后，CLI 会在项目目录下生成：

* `ppio.Dockerfile` - Docker 构建文件
* `.dockerignore` - Docker 忽略文件
* `.ppio-agent.yaml` - Agent 配置文件

***

## 步骤 3: 一键部署到 PPIO 云端

> ⚠️ **重要**：部署成功后会生成 `agent_id`，这是调用 Agent 的唯一标识，请务必记录。

### 3.1 部署命令

使用 CLI 一键部署：

```bash theme={null}
npx ppio-sandbox-cli agent launch
```

### 3.2 查看部署结果

部署成功后，`.ppio-agent.yaml` 文件会更新 `status` 字段：

```yaml theme={null}
status:
  phase: deployed
  agent_id: agent-xxxx  # ⭐ 这是 Agent 的唯一标识
  last_deployed: '2025-10-23T10:35:00Z'
  build_id: build_xyz789
```

**请记录 `agent_id`，后续调用时需要使用。**

***

## 步骤 4: 通过 CLI 或 SDK 调用 Agent

### 方式 1: CLI 快速测试

使用 CLI 快速测试 Agent：

```bash theme={null}
npx ppio-sandbox-cli agent invoke "Hello, Agent!"
```

**注意**：CLI 会自动从 `.ppio-agent.yaml` 的 `status.agent_id` 字段读取 Agent ID。

**预期输出**：

```json theme={null}
{"result": "收到消息: Hello, Agent!"}
```

### 方式 2: SDK 调用（生产环境推荐）

在后端服务中使用 SDK 调用 Agent：

#### 示例代码

```python theme={null}
import asyncio
import json
import os
from ppio_sandbox.agent_runtime import AgentRuntimeClient
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

# 创建 Agent Runtime 客户端
client = AgentRuntimeClient(
    api_key=os.getenv("PPIO_API_KEY")
)

async def main():
    # 部署完成后从 .ppio-agent.yaml 的 status.agent_id 获取
    agent_id = "agent-xxxx"
    
    # 准备请求数据
    payload = json.dumps({
        "prompt": "Hello, Agent! Tell me something about AI."
    }).encode()
    
    # 调用 Agent
    print(f"🚀 Invoking agent: {agent_id}")
    response = await client.invoke_agent_runtime(
        agentId=agent_id,
        payload=payload,
        timeout=300
    )
    
    print(f"✅ Response: {response}")

if __name__ == "__main__":
    asyncio.run(main())
```

***

## 常见问题

### Q1: 如何获取 Agent ID？

部署成功后，Agent ID 保存在 `.ppio-agent.yaml` 文件的 `status.agent_id` 字段：

```yaml theme={null}
status:
  agent_id: agent-xxxxx  # 这里
```

### Q2: 部署失败怎么办？

1. **检查依赖文件**：确保 `requirements.txt` 包含所有依赖
2. **查看详细日志**：使用 `--verbose` 参数
3. **检查网络连接**：确保可以访问 PPIO Sandbox Domain（如 `sandbox.ppio.cn`）
4. **验证 API Key**：确认 `PPIO_API_KEY` 正确

```bash theme={null}
# 显示详细日志
npx ppio-sandbox-cli agent launch --verbose
```

### Q3: 如何更新已部署的 Agent？

修改代码后重新部署即可：

```bash theme={null}
# 方式 1: 创建新版本（推荐）
npx ppio-sandbox-cli agent configure --agent-version 1.1.0
npx ppio-sandbox-cli agent launch

# 方式 2: 更新现有版本
npx ppio-sandbox-cli agent launch --update-existing
```

### Q4: 本地测试正常，部署后调用失败？

**可能原因**：

1. 环境变量未传递到沙箱实例
2. 依赖包版本不一致
3. 文件路径问题

**解决方案**：

通过 `envVars` 参数传递环境变量到沙箱实例：

```python theme={null}
response = await client.invoke_agent_runtime(
    agentId=agent_id,
    payload=payload,
    envVars={
        "PPIO_API_KEY": os.getenv("PPIO_API_KEY"),
        "MODEL_NAME": "deepseek/deepseek-v3-0324"
    }
)
```
