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

# 常见流程

> 常见 API 用例的端到端工作流程指南

本页将介绍使用 Devin API 的常见端到端工作流程。每个流程都包含完整的 API 调用顺序及代码示例。有关各个端点的详细信息，请参阅相关的 API 参考页面。

<div id="setup">
  ## 设置
</div>

在运行任何示例之前，请先设置以下环境变量：

```bash theme={null}
# 必填：你的服务用户 API key（以 cog_ 开头）
export DEVIN_API_KEY="cog_your_key_here"

# 必填：你的组织 ID（在 Settings > Service Users 中查找）
export DEVIN_ORG_ID="your_org_id"
```

***

<div id="getting-started-api-key-to-first-session">
  ## 快速开始：从 API key 到首次会话
</div>

最常见的工作流程——完成身份验证、查看你的账户，并创建你的第一个会话。

<div id="step-1-verify-your-credentials">
  ### 步骤 1：验证你的凭据
</div>

<Note>组织作用域的服务用户可以跳到步骤 3——你已经从 Settings 页面知道了你的 org ID。</Note>

```bash theme={null}
curl "https://api.devin.ai/v3/self" \
  -H "Authorization: Bearer $DEVIN_API_KEY"
```

响应：

```json theme={null}
{
  "principal_type": "service_user",
  "service_user_id": "service-user-abc123",
  "service_user_name": "CI Bot",
  "org_id": null
}
```

<div id="step-2-list-your-organizations">
  ### 步骤 2：列出你的组织
</div>

**企业版服务用户**可以列出所有组织：

```bash theme={null}
curl "https://api.devin.ai/v3/enterprise/organizations" \
  -H "Authorization: Bearer $DEVIN_API_KEY"
```

**组织作用域的服务用户**已经知道其 org ID (可在创建该密钥的 Settings > Service Users 页面上找到) 。

<div id="step-3-create-a-session">
  ### 步骤 3：创建会话
</div>

```bash theme={null}
curl -X POST "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/sessions" \
  -H "Authorization: Bearer $DEVIN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Create a Python script that analyzes CSV data"}'
```

响应：

```json theme={null}
{
  "session_id": "devin-abc123",
  "url": "https://app.devin.ai/sessions/devin-abc123",
  "status": "running"
}
```

<div id="step-4-poll-for-events">
  ### 步骤 4：轮询获取事件
</div>

通过轮询消息来监控会话：

```bash theme={null}
curl "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/sessions/devin-abc123/messages" \
  -H "Authorization: Bearer $DEVIN_API_KEY"
```

<div id="full-python-example">
  ### 完整的 Python 示例
</div>

```python theme={null}
import os
import time
import requests

API_KEY = os.environ["DEVIN_API_KEY"]
ORG_ID = os.environ["DEVIN_ORG_ID"]
BASE = "https://api.devin.ai/v3"
HEADERS = {"Authorization": f"Bearer {API_KEY}"}

# 1. 验证凭据
me = requests.get(f"{BASE}/self", headers=HEADERS)
me.raise_for_status()
data = me.json()
print(f"Authenticated as: {data.get('service_user_name') or data.get('user_name')}")

# 2. 创建会话
session = requests.post(
    f"{BASE}/organizations/{ORG_ID}/sessions",
    headers={**HEADERS, "Content-Type": "application/json"},
    json={"prompt": "Create a Python script that analyzes CSV data"}
).json()
print(f"Session: {session['url']}")

# 3. 轮询直至完成
while True:
    status = requests.get(
        f"{BASE}/organizations/{ORG_ID}/sessions/{session['session_id']}",
        headers=HEADERS
    ).json()["status"]
    print(f"Status: {status}")
    if status in ("exit", "error", "suspended"):
        break
    time.sleep(10)
```

***

<div id="downloading-session-attachments">
  ## 下载会话附件
</div>

获取会话生成的文件 (日志、截图、生成的代码等) 。

<div id="step-1-get-the-session">
  ### 步骤 1：获取会话
</div>

```bash theme={null}
curl "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/sessions/$SESSION_ID" \
  -H "Authorization: Bearer $DEVIN_API_KEY"
```

<div id="step-2-list-attachments">
  ### 步骤 2：列出附件
</div>

```bash theme={null}
curl "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/sessions/$SESSION_ID/attachments" \
  -H "Authorization: Bearer $DEVIN_API_KEY"
```

响应：

```json theme={null}
{
  "items": [
    {
      "attachment_id": "att_123",
      "name": "output.py",
      "url": "https://..."
    }
  ]
}
```

<div id="step-3-download">
  ### 步骤 3：下载
</div>

使用附件响应返回的 `url` 可直接下载文件。

<div id="full-python-example">
  ### 完整的 Python 示例
</div>

```python theme={null}
import os
import requests

API_KEY = os.environ["DEVIN_API_KEY"]
ORG_ID = os.environ["DEVIN_ORG_ID"]
SESSION_ID = os.environ["SESSION_ID"]
BASE = "https://api.devin.ai/v3"
HEADERS = {"Authorization": f"Bearer {API_KEY}"}

# List attachments
attachments = requests.get(
    f"{BASE}/organizations/{ORG_ID}/sessions/{SESSION_ID}/attachments",
    headers=HEADERS
).json()["items"]

# Download each attachment
for att in attachments:
    print(f"Downloading {att['name']}...")
    content = requests.get(att["url"]).content
    with open(att["name"], "wb") as f:
        f.write(content)
    print(f"  Saved {att['name']} ({len(content)} bytes)")
```

***

<div id="knowledge-playbook-management">
  ## Knowledge 和 playbook 管理
</div>

管理 Devin 在多个会话中使用的上下文和指示。

<div id="create-a-knowledge-note">
  ### 创建 Knowledge 笔记
</div>

```bash theme={null}
curl -X POST "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/knowledge/notes" \
  -H "Authorization: Bearer $DEVIN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Coding standards",
    "trigger": "When writing code in any repository",
    "body": "Use TypeScript strict mode. Follow existing code style. Run lint before committing."
  }'
```

<div id="list-knowledge-notes">
  ### 列出 Knowledge 笔记
</div>

```bash theme={null}
curl "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/knowledge/notes" \
  -H "Authorization: Bearer $DEVIN_API_KEY"
```

<div id="update-a-knowledge-note">
  ### 更新 Knowledge 笔记
</div>

```bash theme={null}
curl -X PUT "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/knowledge/notes/$NOTE_ID" \
  -H "Authorization: Bearer $DEVIN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Coding standards (updated)",
    "trigger": "When writing code in any repository",
    "body": "Use TypeScript strict mode. Follow existing code style. Run lint and type-check before committing."
  }'
```

<div id="delete-a-knowledge-note">
  ### 删除 Knowledge 笔记
</div>

```bash theme={null}
curl -X DELETE "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/knowledge/notes/$NOTE_ID" \
  -H "Authorization: Bearer $DEVIN_API_KEY"
```

<div id="create-a-playbook">
  ### 创建 playbook
</div>

```bash theme={null}
curl -X POST "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/playbooks" \
  -H "Authorization: Bearer $DEVIN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "PR Review",
    "instructions": "Review the PR for bugs, security issues, and style violations. Leave inline comments."
  }'
```

<div id="full-python-example">
  ### 完整的 Python 示例
</div>

```python theme={null}
import os
import requests

API_KEY = os.environ["DEVIN_API_KEY"]
ORG_ID = os.environ["DEVIN_ORG_ID"]
BASE = "https://api.devin.ai/v3"
HEADERS = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}

# 创建 Knowledge 笔记
note = requests.post(
    f"{BASE}/organizations/{ORG_ID}/knowledge/notes",
    headers=HEADERS,
    json={
        "name": "Coding standards",
        "trigger": "When writing code in any repository",
        "body": "Use TypeScript strict mode. Follow existing code style."
    }
).json()
print(f"Created note: {note['note_id']}")

# 列出所有笔记
notes = requests.get(
    f"{BASE}/organizations/{ORG_ID}/knowledge/notes",
    headers={"Authorization": f"Bearer {API_KEY}"}
).json()["items"]
print(f"Total notes: {len(notes)}")

# 创建 playbook
playbook = requests.post(
    f"{BASE}/organizations/{ORG_ID}/playbooks",
    headers=HEADERS,
    json={
        "name": "PR Review",
        "instructions": "Review the PR for bugs, security issues, and style violations."
    }
).json()
print(f"Created playbook: {playbook['playbook_id']}")
```

***

<div id="scheduling-automated-sessions">
  ## 设置自动化会话计划
</div>

创建按计划重复运行的会话。

<div id="create-a-schedule">
  ### 创建计划
</div>

```bash theme={null}
curl -X POST "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/schedules" \
  -H "Authorization: Bearer $DEVIN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "Run the test suite and report any failures",
    "cron_schedule": "0 9 * * 1-5",
    "timezone": "America/New_York"
  }'
```

这会创建一个计划，于美国东部时间每个工作日上午 9 点运行。

<div id="list-schedules">
  ### 列出计划
</div>

```bash theme={null}
curl "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/schedules" \
  -H "Authorization: Bearer $DEVIN_API_KEY"
```

<div id="update-a-schedule">
  ### 更新计划
</div>

```bash theme={null}
curl -X PATCH "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/schedules/$SCHEDULE_ID" \
  -H "Authorization: Bearer $DEVIN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "cron_schedule": "0 8 * * 1-5",
    "is_enabled": true
  }'
```

<div id="delete-a-schedule">
  ### 删除计划
</div>

```bash theme={null}
curl -X DELETE "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/schedules/$SCHEDULE_ID" \
  -H "Authorization: Bearer $DEVIN_API_KEY"
```

<div id="full-python-example">
  ### 完整的 Python 示例
</div>

```python theme={null}
import os
import requests

API_KEY = os.environ["DEVIN_API_KEY"]
ORG_ID = os.environ["DEVIN_ORG_ID"]
BASE = "https://api.devin.ai/v3"
HEADERS = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}

# 创建每日健康检查计划
schedule = requests.post(
    f"{BASE}/organizations/{ORG_ID}/schedules",
    headers=HEADERS,
    json={
        "prompt": "Run the test suite and report any failures",
        "cron_schedule": "0 9 * * 1-5",
        "timezone": "America/New_York"
    }
).json()
print(f"Created schedule: {schedule['schedule_id']}")

# 列出所有计划
schedules = requests.get(
    f"{BASE}/organizations/{ORG_ID}/schedules",
    headers={"Authorization": f"Bearer {API_KEY}"}
).json()["items"]

for s in schedules:
    status = "enabled" if s.get("is_enabled") else "disabled"
    print(f"  {s['schedule_id']}: {s['cron_schedule']} ({status})")
```

***

<div id="hand-off-a-task-from-anywhere">
  ## 从任何地方移交任务
</div>

由于 Sessions API 只需一次请求就能创建 cloud Devin 会话，因此任何工具、脚本或代码 Agent 都可以将工作“移交”给 Devin——把当前代码仓库、分支和未提交的更改一并打包到提示中，让云端会话从你离开的地方继续。

<div id="create-a-session-with-repo-context">
  ### 创建带有代码仓库上下文的会话
</div>

```bash theme={null}
# 使用 jq 构建 JSON 请求体，将原始 diff（包含引号、
# 反斜杠和换行符）转义为合法的 JSON 字符串。
curl -X POST "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/sessions" \
  -H "Authorization: Bearer $DEVIN_API_KEY" \
  -H "Content-Type: application/json" \
  -d "$(jq -n --arg diff "$(git diff HEAD)" \
    '{prompt: "Repo: my-org/my-repo (branch: fix-flaky-tests)\nFix the flaky integration tests in CI.\n\nUncommitted changes:\n\($diff)"}')"
```

云端会话会克隆代码仓库，应用你提示中的上下文，并在独立的 VM 中运行，提供 shell、浏览器以及对整个代码仓库的完整访问权限。你可以通过[轮询消息](#step-4-poll-for-events)或在 [Devin web app](https://app.devin.ai) 中跟踪其进度。

<Warning>
  `git diff HEAD` 可能包含未提交的 secrets——API keys、令牌或对 `.env` 的修改——而提示也会上传到云端会话。移交前，请检查你的 diff，并提交、暂存或移除敏感更改。
</Warning>

<Tip>
  不想自己实现这套流程？开源的 [Devin Handoff](https://github.com/club-cog/devin-handoff) 插件正是对这套流程的封装——可自动检测代码仓库、分支和 diff——这样你就可以从 Devin CLI、Claude Code、Codex、Cursor 或普通 shell 脚本发起移交。请参阅[移交给 Devin](/zh/work-with-devin/devin-handoff)。
</Tip>

***

<div id="error-handling">
  ## 错误处理
</div>

以上所有示例在生产环境中都应包含错误处理。下面提供一种可复用的写法：

```python theme={null}
import requests

def api_request(method, url, headers, **kwargs):
    """发起带有标准错误处理的 API 请求。"""
    response = requests.request(method, url, headers=headers, **kwargs)
    try:
        response.raise_for_status()
        return response.json()
    except requests.exceptions.HTTPError as e:
        status = e.response.status_code
        if status == 401:
            raise Exception("Invalid or expired API key")
        elif status == 403:
            raise Exception("Service user lacks required permission")
        elif status == 404:
            raise Exception("Resource not found")
        elif status == 429:
            raise Exception("Rate limit exceeded — wait and retry")
        else:
            raise Exception(f"API error {status}: {e.response.text}")
```

<div id="support">
  ## 支持
</div>

<Card title="需要帮助？">
  如果您对 API 有任何疑问或需要报告问题，请发送电子邮件至 [support@cognition.ai](mailto:support@cognition.ai)
</Card>
