将您的 Crew 部署到 CrewAI 企业版后,它会自动作为 REST API 提供。本指南解释了如何通过编程方式与您的 Crew 进行交互。

API 基础知识

您已部署的 Crew 提供多个端点,允许您

  1. 发现所需的输入
  2. 启动 Crew 执行
  3. 监控执行状态
  4. 接收结果

身份验证

所有 API 请求都需要一个 bearer token 进行身份验证,该 token 在您部署 Crew 时生成

curl -H "Authorization: Bearer YOUR_CREW_TOKEN" https://your-crew-url.crewai.com/...

您可以在 CrewAI 企业版仪表板中,您 Crew 详情页面的“状态”选项卡中找到您的 bearer token。

可用端点

您的 Crew API 提供三个主要端点

端点方法描述
/inputsGET列出 Crew 执行所需的所有输入
/kickoffPOST使用提供的输入启动 Crew 执行
/status/{kickoff_id}GET检索执行的状态和结果

GET /inputs

inputs 端点允许您发现您的 Crew 需要哪些参数

curl -X GET \
  -H "Authorization: Bearer YOUR_CREW_TOKEN" \
  https://your-crew-url.crewai.com/inputs

响应

{
  "inputs": ["budget", "interests", "duration", "age"]
}

此响应表明您的 Crew 期望四个输入参数:budgetinterestsdurationage

POST /kickoff

kickoff 端点启动新的 Crew 执行

curl -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_CREW_TOKEN" \
  -d '{
    "inputs": {
      "budget": "1000 USD",
      "interests": "games, tech, ai, relaxing hikes, amazing food",
      "duration": "7 days",
      "age": "35"
    }
  }' \
  https://your-crew-url.crewai.com/kickoff

请求参数

参数类型必需描述
inputs对象所有必需输入的键值对
meta对象传递给 Crew 的附加元数据
taskWebhookUrl字符串每个任务完成后执行的回调 URL
stepWebhookUrl字符串每个代理思考后执行的回调 URL
crewWebhookUrl字符串Crew 完成后执行的回调 URL

包含 Webhook 的示例

{
  "inputs": {
    "budget": "1000 USD",
    "interests": "games, tech, ai, relaxing hikes, amazing food",
    "duration": "7 days",
    "age": "35"
  },
  "meta": {
    "requestId": "user-request-12345",
    "source": "mobile-app"
  },
  "taskWebhookUrl": "https://your-server.com/webhooks/task",
  "stepWebhookUrl": "https://your-server.com/webhooks/step",
  "crewWebhookUrl": "https://your-server.com/webhooks/crew"
}

响应

{
  "kickoff_id": "abcd1234-5678-90ef-ghij-klmnopqrstuv"
}

kickoff_id 用于跟踪和检索执行结果。

GET /status/

status 端点允许您检查 Crew 执行的进度和结果

curl -X GET \
  -H "Authorization: Bearer YOUR_CREW_TOKEN" \
  https://your-crew-url.crewai.com/status/abcd1234-5678-90ef-ghij-klmnopqrstuv

响应结构

响应结构将根据执行状态而异

进行中

{
  "status": "running",
  "current_task": "research_task",
  "progress": {
    "completed_tasks": 0,
    "total_tasks": 2
  }
}

已完成

{
  "status": "completed",
  "result": {
    "output": "Comprehensive travel itinerary...",
    "tasks": [
      {
        "task_id": "research_task",
        "output": "Research findings...",
        "agent": "Researcher",
        "execution_time": 45.2
      },
      {
        "task_id": "planning_task",
        "output": "7-day itinerary plan...",
        "agent": "Trip Planner",
        "execution_time": 62.8
      }
    ]
  },
  "execution_time": 108.5
}

Webhook 集成

当您在启动请求中提供 webhook URL 时,系统将在执行过程中的特定点向这些 URL 发出 POST 请求

taskWebhookUrl

每个任务完成后调用

{
  "kickoff_id": "abcd1234-5678-90ef-ghij-klmnopqrstuv",
  "task_id": "research_task",
  "status": "completed",
  "output": "Research findings...",
  "agent": "Researcher",
  "execution_time": 45.2
}

stepWebhookUrl

每个代理思考或行动后调用

{
  "kickoff_id": "abcd1234-5678-90ef-ghij-klmnopqrstuv",
  "task_id": "research_task",
  "agent": "Researcher",
  "step_type": "thought",
  "content": "I should first search for popular destinations that match these interests..."
}

crewWebhookUrl

整个 Crew 执行完成后调用

{
  "kickoff_id": "abcd1234-5678-90ef-ghij-klmnopqrstuv",
  "status": "completed",
  "result": {
    "output": "Comprehensive travel itinerary...",
    "tasks": [
      {
        "task_id": "research_task",
        "output": "Research findings...",
        "agent": "Researcher",
        "execution_time": 45.2
      },
      {
        "task_id": "planning_task",
        "output": "7-day itinerary plan...",
        "agent": "Trip Planner",
        "execution_time": 62.8
      }
    ]
  },
  "execution_time": 108.5,
  "meta": {
    "requestId": "user-request-12345",
    "source": "mobile-app"
  }
}

最佳实践

处理长时间运行的执行

Crew 执行可能需要几秒到几分钟,具体取决于其复杂性。请考虑以下方法

  1. Webhooks(推荐):设置 webhook 端点以在执行完成时接收通知
  2. 轮询:实现具有指数退避的轮询机制
  3. 客户端超时:为您的 API 请求设置适当的超时

错误处理

API 可能会返回各种错误代码

代码描述推荐操作
401未授权检查您的 bearer token
404未找到验证您的 crew URL 和 kickoff_id
422验证错误确保提供了所有必需的输入
500服务器错误联系支持团队并提供错误详情

示例代码

以下是一个与您的 crew API 进行交互的完整 Python 示例

import requests
import time

# Configuration
CREW_URL = "https://your-crew-url.crewai.com"
BEARER_TOKEN = "your-crew-token"
HEADERS = {
    "Authorization": f"Bearer {BEARER_TOKEN}",
    "Content-Type": "application/json"
}

# 1. Get required inputs
response = requests.get(f"{CREW_URL}/inputs", headers=HEADERS)
required_inputs = response.json()["inputs"]
print(f"Required inputs: {required_inputs}")

# 2. Start crew execution
payload = {
    "inputs": {
        "budget": "1000 USD",
        "interests": "games, tech, ai, relaxing hikes, amazing food",
        "duration": "7 days",
        "age": "35"
    }
}

response = requests.post(f"{CREW_URL}/kickoff", headers=HEADERS, json=payload)
kickoff_id = response.json()["kickoff_id"]
print(f"Execution started with ID: {kickoff_id}")

# 3. Poll for results
MAX_RETRIES = 30
POLL_INTERVAL = 10  # seconds
for i in range(MAX_RETRIES):
    print(f"Checking status (attempt {i+1}/{MAX_RETRIES})...")
    response = requests.get(f"{CREW_URL}/status/{kickoff_id}", headers=HEADERS)
    data = response.json()
    
    if data["status"] == "completed":
        print("Execution completed!")
        print(f"Result: {data['result']['output']}")
        break
    elif data["status"] == "error":
        print(f"Execution failed: {data.get('error', 'Unknown error')}")
        break
    else:
        print(f"Status: {data['status']}, waiting {POLL_INTERVAL} seconds...")
        time.sleep(POLL_INTERVAL)

需要帮助?

请联系我们的支持团队,获取 API 集成或故障排除方面的帮助。