> ## 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.

# v1 使用示例

> v1 API 的代码示例和常见用例

本页提供 v1 API 的常见用例代码示例。

## 快速示例

> **创建和监控会话**
>
> ```python theme={null}
> import os
> import requests
> import time
>
> DEVIN_API_KEY = os.getenv("DEVIN_API_KEY")
>
> # 创建一个新会话
> response = requests.post(
>     "https://api.devin.ai/v1/sessions",
>     headers={"Authorization": f"Bearer {DEVIN_API_KEY}"},
>     json={
>         "prompt": "Review PR #249",
>         "idempotent": True
>     }
> )
>
> print("Response:\n"+ str(response.json()))
> session_id = response.json()["session_id"]
>
> # 监控会话状态
> while True:
>     status = requests.get(
>         f"https://api.devin.ai/v1/sessions/{session_id}",
>         headers={"Authorization": f"Bearer {DEVIN_API_KEY}"}
>     ).json()
>     print("Status:\n" + str(status))
>     if status["status_enum"] in ["blocked", "finished"]:
>         break
>     time.sleep(5)
> ```

> **文件上传和处理**
>
> ```python theme={null}
> import os
> import requests
>
> DEVIN_API_KEY = os.getenv("DEVIN_API_KEY")
>
> # 上传文件
> with open("data.csv", "rb") as f:
>     response = requests.post(
>         "https://api.devin.ai/v1/attachments",
>         headers={"Authorization": f"Bearer {DEVIN_API_KEY}"},
>         files={"file": f}
>     )
> file_url = response.text
>
> # 创建会话以处理该文件
> response = requests.post(
>     "https://api.devin.ai/v1/sessions",
>     headers={"Authorization": f"Bearer {DEVIN_API_KEY}"},
>     json={
>         "prompt": f"Analyze the data in the attached file.\n\nATTACHMENT:\"{file_url}\""
>     }
> )
>
> print(str(response.json()))
> ```

> **交互式会话**
>
> ```python theme={null}
> import os
> import requests
>
> DEVIN_API_KEY = os.getenv("DEVIN_API_KEY")
>
> # 向活动会话发送消息
> requests.post(
>     f"https://api.devin.ai/v1/sessions/{session_id}/message",
>     headers={"Authorization": f"Bearer {DEVIN_API_KEY}"},
>     json={
>         "message": "Make sure to write units tests when you are done."
>     }
> )
> ```

> **使用会话机密**
>
> 会话机密允许你提供仅在单个会话中可用的临时凭证或 API key，并且不会将其存储到你所在组织的机密配置中。
>
> ```python theme={null}
> import os
> import requests
>
> DEVIN_API_KEY = os.getenv("DEVIN_API_KEY")
>
> # 创建一个带有会话专属密钥的会话
> response = requests.post(
>     "https://api.devin.ai/v1/sessions",
>     headers={"Authorization": f"Bearer {DEVIN_API_KEY}"},
>     json={
>         "prompt": "Deploy the application to the staging environment",
>         "session_secrets": [
>             {
>                 "key": "DEPLOY_API_KEY",
>                 "value": "your-temporary-deploy-key",
>                 "sensitive": True
>             },
>             {
>                 "key": "STAGING_URL",
>                 "value": "https://staging.example.com",
>                 "sensitive": False
>             }
>         ]
>     }
> )
>
> print(response.json())
> ```
>
> **注意：**
>
> * Secret key 名称必须符合环境变量命名规范（以字母或下划线开头，后接字母、数字或下划线）
> * 如果未显式指定，`sensitive` 字段默认为 `true`
> * 会话密钥仅在创建它们的那个会话中可用，不会保存为组织密钥

> **GitHub 仓库分析**
>
> 以下是一个完整示例，演示如何使用 Devin API 分析 GitHub 仓库。本示例涵盖：
>
> * 身份验证和错误处理
> * 创建和监控会话
> * 处理结构化输出
> * 通过 async/await 正确管理资源
>
> ```python theme={null}
> import os
> import aiohttp
> import asyncio
> from typing import List, Dict
>
> API_KEY = os.getenv("DEVIN_API_KEY")
> API_BASE = "https://api.devin.ai/v1"
>
> async def count_stars(session: aiohttp.ClientSession, repo_url: str) -> int:
>     """使用 Devin 统计 GitHub 仓库的 star 数。"""
>     # Create a new Devin session
>     async with session.post(
>         f"{API_BASE}/sessions",
>         json={"prompt": f"Count stars for GitHub repository: {repo_url}"}
>     ) as response:
>         session_data = await response.json()
>         session_id = session_data["session_id"]
>         print(f"Created session {session_id} for {repo_url}")
>         print(f"URL: {session_data['url']}")
>
>     # Poll for results with exponential backoff
>     backoff = 1
>     print("Polling for results...")
>     while True:
>         async with session.get(
>             f"{API_BASE}/sessions/{session_id}"
>         ) as response:
>             response_json = await response.json()
>             if response_json["status_enum"] in ["blocked", "finished"]:
>                 return response_json["structured_output"].get("star_count", 0)
>         await asyncio.sleep(min(backoff, 30))
>         backoff *= 2
>
> async def main():
>     """Main function to analyze GitHub repositories."""
>     headers = {"Authorization": f"Bearer {API_KEY}"}
>     async with aiohttp.ClientSession(headers=headers) as session:
>         # Example repositories to analyze
>         repos = [
>             "https://github.com/openai/openai-python",
>             "https://github.com/anthropics/anthropic-sdk-python"
>         ]
>
>         # Count stars for each repository
>         for repo in repos:
>             stars = await count_stars(session, repo)
>             print(f"{repo}: {stars} stars")
>
> if __name__ == "__main__":
>     asyncio.run(main())
> ```

## 高级示例

> **[自动化 QA 测试](https://github.com/CognitionAI/qa-devin)**
>
> 了解我们如何使用 Devin 为 Devin 本身做 QA 测试。利用 Devin 的浏览器能力实现端到端测试自动化。

> **[自动化 PR 审查](https://cognition.com/blog/devin-101-automatic-pr-reviews-with-the-devin-api)**
>
> 了解如何将 Devin 与 GitHub Actions 集成，实现 PR 自动化审查。

## 支持

> **需要帮助？**
>
> 如需咨询 API 相关问题或报告故障，请发送邮件至 [support@cognition.ai](mailto:support@cognition.ai)。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.