跳轉到

Chat API

Chat API 讓你能夠以程式化方式建立聊天會話、發送訊息,並接收 AI Agent 的回應。

列出已發布的 Agent

取得你的工作空間中所有已發布的 Agent。

端點: GET /api/v1/chats/published-agents

請求

curl -X GET "https://api.codeer.ai/api/v1/chats/published-agents" \
  -H "x-api-key: YOUR_API_KEY"

回應

{
  "data": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "客服 Agent",
      "description": "處理客戶諮詢",
      "workspace_id": "workspace-uuid-here",
      "publish_state": "public",
      "agent_type": "basic",
      "created_at": "2024-01-15T10:30:00Z",
      "updated_at": "2024-01-15T10:30:00Z"
    }
  ],
  "message": null,
  "error_code": 0
}

回應欄位

回應包含額外欄位如 system_promptunified_toolssuggested_questionsuse_searchmetallm_model 和版本相關欄位。完整 schema 請參閱程式碼庫。


建立聊天

使用特定 Agent 建立新的聊天會話。

端點: POST /api/v1/chats

請求內容

欄位 類型 必填 說明
name string 聊天會話名稱(最多 256 個字元)
agent_id UUID Agent 的 ID(必須有已發布版本)
external_user_id string 條件式 你系統中的用戶識別碼。如果工作空間啟用白名單模式則為必填。

Agent 必須已發布

雖然 API 接受任何有效的 agent_id,但只有當 Agent 有已發布版本時聊天才能使用。嘗試向使用未發布 Agent 建立的聊天發送訊息將回傳「Agent version not found」訊息的 404 Not Found。請使用列出已發布的 Agent端點取得有效的 Agent ID。

範例

curl -X POST "https://api.codeer.ai/api/v1/chats" \
  -H "x-api-key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "客服會話",
    "agent_id": "550e8400-e29b-41d4-a716-446655440000",
    "external_user_id": "user_123"
  }'

回應

{
  "data": {
    "id": 12345,
    "name": "客服會話",
    "meta": {
      "external_user_id": "user_123",
      "conversation_agent_id": "550e8400-e29b-41d4-a716-446655440000"
    },
    "external_user_id": "user_123",
    "created_at": "2024-01-15T10:30:00Z",
    "updated_at": "2024-01-15T10:30:00Z"
  },
  "message": null,
  "error_code": 0
}

列出聊天

取得聊天會話,支援分頁和篩選。

端點: GET /api/v1/chats

查詢參數

參數 類型 預設值 說明
limit integer 50 每頁結果數(最多 1000)
offset integer 0 跳過的結果數
order_by string -created_at 排序方式:created_at-created_atascdesc
agent_id UUID - 依 Agent 篩選
external_user_id string - 依外部用戶篩選

範例

curl -X GET "https://api.codeer.ai/api/v1/chats?limit=10&agent_id=550e8400-e29b-41d4-a716-446655440000" \
  -H "x-api-key: YOUR_API_KEY"

回應

{
  "data": [
    {
      "id": 12345,
      "name": "客服會話",
      "meta": { ... },
      "external_user_id": "user_123",
      "created_at": "2024-01-15T10:30:00Z",
      "updated_at": "2024-01-15T10:35:00Z"
    }
  ],
  "pagination": {
    "limit": 10,
    "offset": 0,
    "total_records": 100,
    "total_pages": 10,
    "current_page": 1,
    "next_page": "https://api.codeer.ai/api/v1/chats?offset=10&limit=10",
    "prev_page": null
  },
  "message": null,
  "error_code": 0
}

取得聊天訊息

取得特定聊天的訊息記錄。

端點: GET /api/v1/chats/{chat_id}/messages

路徑參數

參數 類型 說明
chat_id integer 聊天會話 ID

查詢參數

參數 類型 預設值 說明
limit integer 50 每頁結果數
offset integer 0 跳過的結果數
external_user_id string - 你系統中的使用者識別碼。使用 API 金鑰認證時為必填。也可透過 x-external-user-id 標頭傳遞。

範例

curl -X GET "https://api.codeer.ai/api/v1/chats/12345/messages?external_user_id=user_123" \
  -H "x-api-key: YOUR_API_KEY"

回應

{
  "data": [
    {
      "id": 1001,
      "role": "user",
      "group_id": "group_abc",
      "content": "你好,我需要訂單方面的協助",
      "meta": {},
      "attached_files": [],
      "feedback_counts": {}
    },
    {
      "id": 1002,
      "role": "assistant",
      "group_id": "group_abc",
      "content": "你好!我很樂意協助你處理訂單問題。請問你可以提供訂單編號嗎?",
      "meta": {
        "reasoning_steps": [...],
        "token_usage": {
          "total_prompt_tokens": 150,
          "total_completion_tokens": 45,
          "total_tokens": 195,
          "total_calls": 1
        }
      },
      "attached_files": [],
      "feedback_counts": {
        "sys_helpful": 1
      }
    }
  ],
  "pagination": { ... },
  "message": null,
  "error_code": 0
}

發送訊息

向聊天發送訊息並接收 Agent 的回應。支援串流(SSE)和非串流兩種模式。

端點: POST /api/v1/chats/{chat_id}/messages

路徑參數

參數 類型 說明
chat_id integer 聊天會話 ID

請求內容

欄位 類型 必填 說明
message string 用戶的訊息
stream boolean 啟用 SSE 串流(預設:true
agent_id UUID Agent ID(必須與聊天的 Agent 相符)
attached_file_uuids array 要附加的已上傳檔案 UUID
external_user_id string 條件式 你系統中的用戶識別碼。如果工作空間啟用白名單模式則為必填。

可能的錯誤回應

  • 404 Not Found「Agent not found」- agent_id 不存在於此工作空間
  • 404 Not Found「Agent version not found」- Agent 存在但沒有已發布版本
  • 404 Not Found「Chat not found」- chat_id 不存在
  • 400 Bad Request「Agent mismatch」- agent_id 與建立聊天時使用的 Agent 不符
  • 403 Forbidden 錯誤代碼 14103 - 工作空間啟用白名單模式且 external_user_id 缺少或未在白名單中

非串流範例

curl -X POST "https://api.codeer.ai/api/v1/chats/12345/messages" \
  -H "x-api-key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "message": "你們的營業時間是?",
    "stream": false,
    "agent_id": "550e8400-e29b-41d4-a716-446655440000"
  }'

非串流回應

{
  "data": "我們的營業時間是週一至週五,上午 9 點到下午 6 點。週末和主要節日休息。還有什麼關於營業時間的問題嗎?",
  "message": null,
  "error_code": 0
}

串流範例

curl -N -X POST "https://api.codeer.ai/api/v1/chats/12345/messages" \
  -H "x-api-key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Accept: text/event-stream" \
  -d '{
    "message": "你們的營業時間是?",
    "stream": true,
    "agent_id": "550e8400-e29b-41d4-a716-446655440000"
  }'

關於串流回應的詳細資訊,請參閱 SSE 串流


上傳檔案

上傳檔案以附加到聊天訊息。

端點: POST /api/v1/chats/upload-file

限制

限制
最大檔案大小 50 MB
允許的 MIME 類型 application/pdftext/*application/mswordapplication/vnd.openxmlformats-officedocument.wordprocessingml.documentapplication/vnd.openxmlformats-officedocument.presentationml.presentationimage/jpegimage/pngimage/gifimage/webptext/html
允許的副檔名 .pdf.txt.md.csv.docx.doc.pptx.jpeg.jpg.png.gif.webp.html

請求

使用 multipart/form-data 編碼:

欄位 類型 必填 說明
file binary 要上傳的檔案
data JSON string 包含 scope 欄位的 JSON 物件(persistentephemeral,預設:persistent

範例

curl -X POST "https://api.codeer.ai/api/v1/chats/upload-file" \
  -H "x-api-key: YOUR_API_KEY" \
  -F "file=@document.pdf" \
  -F 'data={"scope":"persistent"}'

回應

{
  "data": {
    "uuid": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    "original_name": "document.pdf",
    "content_type": "application/pdf",
    "size": 102400,
    "file_url": "https://storage.codeer.ai/files/...",
    "scope": "persistent"
  },
  "message": null,
  "error_code": 0
}

錯誤回應

當驗證失敗時,回應的 data 中會包含 error_msg 欄位:

{
  "data": {
    "original_name": "large-file.pdf",
    "content_type": "application/pdf",
    "size": 104857600,
    "scope": "persistent",
    "error_msg": "File size check failed (max size: 50 MB)"
  },
  "message": "File size check failed (max size: 50 MB)",
  "error_code": 10006
}

常見的驗證錯誤:

  • "File size check failed (max size: 50 MB)" - 檔案超過 50 MB 限制
  • "Unsupported content type: {type}" - MIME 類型不在允許清單中
  • "Unsupported file extension: {ext}" - 副檔名不在允許清單中
  • "File name is missing" - 未提供檔案名稱
  • "File is empty (size must be greater than 0 bytes)" - 檔案是空的

使用已上傳的檔案

上傳後,在發送訊息時加入檔案 UUID:

curl -X POST "https://api.codeer.ai/api/v1/chats/12345/messages" \
  -H "x-api-key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "message": "請分析這份文件",
    "stream": true,
    "agent_id": "550e8400-e29b-41d4-a716-446655440000",
    "attached_file_uuids": ["a1b2c3d4-e5f6-7890-abcd-ef1234567890"]
  }'

建立訊息回饋

對助理的回應提交回饋。

端點: POST /api/v1/chats/{chat_id}/messages/{message_id}/feedbacks

路徑參數

參數 類型 說明
chat_id integer 聊天會話 ID
message_id integer 要提供回饋的訊息 ID

請求內容

欄位 類型 必填 說明
external_user_id string 你系統中的用戶識別碼
type string 回饋類型:sys_helpfulsys_improve
content string 額外的回饋文字(僅適用於 sys_improve 類型,最多 500 個字元)

範例

curl -X POST "https://api.codeer.ai/api/v1/chats/12345/messages/1002/feedbacks" \
  -H "x-api-key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "external_user_id": "user_123",
    "type": "sys_helpful"
  }'

回應

{
  "message": "Feedback created",
  "error_code": 0
}

程式碼範例

Python

import requests

API_KEY = "your-api-key"
BASE_URL = "https://api.codeer.ai/api/v1"

headers = {
    "x-api-key": API_KEY,
    "Content-Type": "application/json"
}

# 建立聊天
chat_response = requests.post(
    f"{BASE_URL}/chats",
    headers=headers,
    json={
        "name": "API 測試",
        "agent_id": "your-agent-id",
        "external_user_id": "user_123"
    }
)
chat_id = chat_response.json()["data"]["id"]

# 發送訊息(非串流)
message_response = requests.post(
    f"{BASE_URL}/chats/{chat_id}/messages",
    headers=headers,
    json={
        "message": "你好!",
        "stream": False,
        "agent_id": "your-agent-id"
    }
)
print(message_response.json()["data"])

JavaScript

const API_KEY = 'your-api-key';
const BASE_URL = 'https://api.codeer.ai/api/v1';

const headers = {
  'x-api-key': API_KEY,
  'Content-Type': 'application/json'
};

// 建立聊天
const chatResponse = await fetch(`${BASE_URL}/chats`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    name: 'API 測試',
    agent_id: 'your-agent-id',
    external_user_id: 'user_123'
  })
});
const { data: chat } = await chatResponse.json();

// 發送訊息(非串流)
const messageResponse = await fetch(`${BASE_URL}/chats/${chat.id}/messages`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    message: '你好!',
    stream: false,
    agent_id: 'your-agent-id'
  })
});
const { data: reply } = await messageResponse.json();
console.log(reply);

更多範例包括串流實作,請參閱官方範例儲存庫