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

设置

在运行任何示例之前,请先设置以下环境变量:
# 必填:你的服务用户 API key(以 cog_ 开头)
export DEVIN_API_KEY="cog_your_key_here"

# 必填:你的组织 ID(在 Settings > Service Users 中查找)
export DEVIN_ORG_ID="your_org_id"

快速开始:从 API key 到首次会话

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

步骤 1:验证你的凭据

组织作用域的服务用户可以跳到步骤 3——你已经从 Settings 页面知道了你的 org ID。
curl "https://api.devin.ai/v3/self" \
  -H "Authorization: Bearer $DEVIN_API_KEY"
响应:
{
  "principal_type": "service_user",
  "service_user_id": "service-user-abc123",
  "service_user_name": "CI Bot",
  "org_id": null
}

步骤 2:列出你的组织

企业版服务用户可以列出所有组织:
curl "https://api.devin.ai/v3/enterprise/organizations" \
  -H "Authorization: Bearer $DEVIN_API_KEY"
组织作用域的服务用户已经知道其 org ID (可在创建该密钥的 Settings > Service Users 页面上找到) 。

步骤 3:创建会话

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"}'
响应:
{
  "session_id": "devin-abc123",
  "url": "https://app.devin.ai/sessions/devin-abc123",
  "status": "running"
}

步骤 4:轮询获取事件

通过轮询消息来监控会话:
curl "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/sessions/devin-abc123/messages" \
  -H "Authorization: Bearer $DEVIN_API_KEY"

完整的 Python 示例

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)

下载会话附件

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

步骤 1:获取会话

curl "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/sessions/$SESSION_ID" \
  -H "Authorization: Bearer $DEVIN_API_KEY"

步骤 2:列出附件

curl "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/sessions/$SESSION_ID/attachments" \
  -H "Authorization: Bearer $DEVIN_API_KEY"
响应:
{
  "items": [
    {
      "attachment_id": "att_123",
      "name": "output.py",
      "url": "https://..."
    }
  ]
}

步骤 3:下载

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

完整的 Python 示例

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)")

Knowledge 和 playbook 管理

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

创建 Knowledge 笔记

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."
  }'

列出 Knowledge 笔记

curl "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/knowledge/notes" \
  -H "Authorization: Bearer $DEVIN_API_KEY"

更新 Knowledge 笔记

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."
  }'

删除 Knowledge 笔记

curl -X DELETE "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/knowledge/notes/$NOTE_ID" \
  -H "Authorization: Bearer $DEVIN_API_KEY"

创建 playbook

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."
  }'

完整的 Python 示例

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']}")

设置自动化会话计划

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

创建计划

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 点运行。

列出计划

curl "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/schedules" \
  -H "Authorization: Bearer $DEVIN_API_KEY"

更新计划

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
  }'

删除计划

curl -X DELETE "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/schedules/$SCHEDULE_ID" \
  -H "Authorization: Bearer $DEVIN_API_KEY"

完整的 Python 示例

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})")

从任何地方移交任务

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

创建带有代码仓库上下文的会话

# 使用 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、浏览器以及对整个代码仓库的完整访问权限。你可以通过轮询消息或在 Devin web app 中跟踪其进度。
git diff HEAD 可能包含未提交的 secrets——API keys、令牌或对 .env 的修改——而提示也会上传到云端会话。移交前,请检查你的 diff,并提交、暂存或移除敏感更改。
不想自己实现这套流程?开源的 Devin Handoff 插件正是对这套流程的封装——可自动检测代码仓库、分支和 diff——这样你就可以从 Devin CLI、Claude Code、Codex、Cursor 或普通 shell 脚本发起移交。请参阅移交给 Devin

错误处理

以上所有示例在生产环境中都应包含错误处理。下面提供一种可复用的写法:
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}")

支持

需要帮助?

如果您对 API 有任何疑问或需要报告问题,请发送电子邮件至 support@cognition.ai